Can I recreate this using commands?

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

Réponses (1)

DGM
DGM le 31 Jan 2022
Modifié(e) : DGM le 31 Jan 2022
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Modifié(e) :

DGM
le 31 Jan 2022

Community Treasure Hunt

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

Start Hunting!

Translated by