简体   繁体   中英

What is the Matlab/Octave equivalent or R's 'merge' (or 'expand.grid')?

I am looking for the Matlab way of doing the following:

> merge(2:4,3:7)
   x y
1  2 3
2  3 3
3  4 3
4  2 4
5  3 4
6  4 4
7  2 5
8  3 5
9  4 5
10 2 6
11 3 6
12 4 6
13 2 7
14 3 7
15 4 7
> expand.grid(2:4,3:7)
   Var1 Var2
1     2    3
2     3    3
3     4    3
4     2    4
5     3    4
6     4    4
7     2    5
8     3    5
9     4    5
10    2    6
11    3    6
12    4    6
13    2    7
14    3    7
15    4    7

I usually do it with meshgrid :

>> [x y] = meshgrid(2:4, 3:7);
>> [x(:) y(:)]

ans =

     2     3
     2     4
     2     5
     2     6
     2     7
     3     3
     3     4
     3     5
     3     6
     3     7
     4     3
     4     4
     4     5
     4     6
     4     7

Use ndgrid for n variables (2 and more). For example (4-D space)

[X,Y,Z,T] = ndgrid(2:4, 3:7, 1:2, 1:10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM