How to code with for loop loops without using ndgrid?

조회 수: 1 (최근 30일)
Meliha Basturk
Meliha Basturk 2021년 10월 27일
답변: Stephen23 2021년 10월 27일
Hello, how do I write the following code without ndgrid, that is, with for loop loops, without using a ready-made library.
[A B C]=ndgrid(1:2,3:4,5:6);
A1=reshape(A,[],1);
B1=reshape(B,[],1);
C1=reshape(C,[],1);
d=[A1,B1,C1]

답변 (2개)

David Hill
David Hill 2021년 10월 27일
count=0;
for c=5:6
for b=3:4
for a=1:2
count=count+1;
d(count,:)=[a,b,c];
end
end
end

Stephen23
Stephen23 2021년 10월 27일
As this is clearly homework, this should get you started:
inp = {1:2, 3:4, 5:6};
[A,B,C] = ndgrid(inp{:});
A1=reshape(A,[],1);
B1=reshape(B,[],1);
C1=reshape(C,[],1);
d=[A1,B1,C1]
d = 8×3
1 3 5 2 3 5 1 4 5 2 4 5 1 3 6 2 3 6 1 4 6 2 4 6
S = cellfun(@numel,inp);
reshape(repmat(reshape(inp{1},S(1),1,1),1,S(2),S(3)),[],1)
ans = 8×1
1 2 1 2 1 2 1 2

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by