Improve code performance with fewer operations

There are two vectors:

a = 1:5;
b = 1:2;

To find all combinations of these two vectors, I use the following code snippet:

[A,B] = meshgrid(a,b);
C = cat(2,A',B');
D = reshape(C,[],2);

The result includes all combinations:

D =

     1     1
     2     1
     3     1
     4     1
     5     1
     1     2
     2     2
     3     2
     4     2
     5     2

now questions:

1- I want to reduce the number of operations in order to improve performance for larger vectors. Is there any one function in MATLAB that does this?

2- In the case where the number of vectors is more than 2, the meshgrid function can not be used and must be replaced with contours for . What is the best solution?

+3
source share
2 answers

For more than two measurements, use ndgrid:

>> a = 1:2; b = 1:3; c = 1:2;
>> [A,B,C] = ndgrid(a,b,c);
>> D = [A(:) B(:) C(:)]
D =
     1     1     1
     2     1     1
     1     2     1
     2     2     1
     1     3     1
     2     3     1
     1     1     2
     2     1     2
     1     2     2
     2     2     2
     1     3     2
     2     3     2

, ndgrid (, ,...), (x, y).

N (. ):

params = {a,b,c};
vecs = cell(numel(params),1);
[vecs{:}] = ndgrid(params{:});
D = reshape(cat(numel(vecs)+1,vecs{:}),[],numel(vecs));

, Robert P. answer , kron () .

, combvec, .

+3

- repmat :

[repmat(a,size(b)); kron(b,ones(size(a)))]'
ans =

     1     1
     2     1
     3     1
     4     1
     5     1
     1     2
     2     2
     3     2
     4     2
     5     2

:

a = 1:3;
b = 1:3;
c = 1:3;

x = [repmat(a,1,numel(b)*numel(c)); ...
     repmat(kron(b,ones(1,numel(a))),1,numel(c)); ...
     kron(c,ones(1,numel(a)*numel(b)))]'

! : . -: . -: ( ) ( , .

+1

All Articles