Can I recreate this using commands?
Show older comments
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
Answers (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
% without a loop
k = 0:D-1;
a = reshape(k.' + k*L + permute(k,[1 3 2])*L^2,1,[])
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!