Is it possible to create the same output as these nested for loops without requiring the loops. I need the output to be a function of L and D so that I can vary the sizes of them later on. The output looks like this a= [ 0 1 4 5 16 17 20 21]
L = 4;
D = 2;
o = 0;
for i = 1:D
for j = 1:D
for k = 1:D
o = o + 1;
a(o) = (k-1) + (j-1)*L + (i-1)*L^2;
end
end
end

답변 (1개)

DGM
DGM 2022년 1월 31일
편집: DGM 2022년 1월 31일

1 개 추천

Here's one way using implicit array expansion.
L = 4;
D = 2;
% using a loop
o = 0;
for i = 1:D
for j = 1:D
for k = 1:D
o = o + 1;
a(o) = (k-1) + (j-1)*L + (i-1)*L^2;
end
end
end
a
a = 1×8
0 1 4 5 16 17 20 21
% without a loop
k = 0:D-1;
a = reshape(k.' + k*L + permute(k,[1 3 2])*L^2,1,[])
a = 1×8
0 1 4 5 16 17 20 21

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2022년 1월 31일

편집:

DGM
2022년 1월 31일

Community Treasure Hunt

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

Start Hunting!

Translated by