I made this code;
x = [0 1]'; y = [0 1]';
m = 2; n = 1;
cell = {x, x, y}; % 2 x and 1 y
[a_1 a_2 b_1] = ndgrid(cell{:});
a_1 = a_1(:); a_2 = a_2(:);
b_1 = b_1(:);
But if I generalise this, by assigning x, y, m, n,
How can I make ... parts?
cell = {x, ... , x, y, ... , y}; % m Xs and n Ys
[a_1 a_2 ... a_m b_1 ... b_n] = ndgrid(cell{:});
a_1 = a_1(:); ... a_m = a_m(:);
b_1 = b_1(:); ... b_n = b_n(:);
Thanks to all!

2 Kommentare

Jan
Jan am 30 Jul. 2018
For the problem concerning hiding indices in the names of variables see Why and how to avoid eval. I will not post a solution, because this method is known to cause more troubles, than it solves.
Guillaume
Guillaume am 30 Jul. 2018
In addition to Jan's comment, do not name your variable cell, since it will prevent you from using the cell function.
Numbered variables are always an indication that your design is wrong. You should never have variables a_1, a_2, ... Instead you should have just one a variable (a cell array, a matrix, whatever is appropriate) that you index, e.g. a(1), a(2), ... With that design the ndgrid assignment is trivial.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Guillaume
Guillaume am 30 Jul. 2018

1 Stimme

As per my comment to your question: numbered variables are always an indication that your design is wrong. You should never have variables a_1, a_2, ... Instead you should have just one a variable (a cell array, a matrix, whatever is appropriate) that you index, e.g. a(1), a(2), ... With that design the ndgrid assignment is trivial.
%demo data
x = [0 1]'; y = [1 0]';
m = 10; n = 7;
c = repelem({x, y}, [m, n]); %creates {x, ... , x, y, ... , y}; % m Xs and n Ys
[c{:}] = ndgrid(c{:}); %ndgrid
c = reshape(cat(m+n+1, c{:}), [], m+n);
a = c(:, 1:m);
b = c(:, m+1:end);
a(:, i) is your a_i, b(:, i) is your b_i.

Weitere Antworten (1)

Stephen23
Stephen23 am 30 Jul. 2018
Bearbeitet: Stephen23 am 30 Jul. 2018

1 Stimme

This is easy when you sensibly store data in one array:
>> x = [0,1];
>> y = [0,1];
>> c = {x,x,y};
>> d = cell(size(c));
>> [d{:}] = ndgrid(c{:});
>> d = cellfun(@(m)m(:),d,'uni',0);
>> d{:}
ans =
0
1
0
1
0
1
0
1
ans =
0
0
1
1
0
0
1
1
ans =
0
0
0
0
1
1
1
1
I recommend putting the output into one numeric matrix:
>> M = [d{:}]
M =
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1
or without the cellfun call:
>> [d{:}] = ndgrid(c{:});
>> M = reshape(cat(3,d{:}),[],numel(d))
M =
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1
See:

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Hilfe-Center und File Exchange

Gefragt:

W K
am 30 Jul. 2018

Bearbeitet:

am 30 Jul. 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by