How can I store vectors from three loops?

1 Ansicht (letzte 30 Tage)
Sari Mira
Sari Mira am 24 Jul. 2014
Kommentiert: dpb am 26 Jul. 2014
Hello everyone,
I'm running into this problem in my code where I have three for loops within each other and I would like to save the results as a function of all three loop variables. I have not been able to figure out how to do that. Below is a sample code of what I have in order to show the problem more clearly than my phrasing of the question. In the example below, I'm trying to save d as a function of i, j, and k. I tried doing d(i,j,k), but that doesn't work.
for i = 1:10
for j = 2:30
for k = 3:50
a = 10*i;
b = 20*j*i;
c = 40*k;
d = a*b/c;
end
end
end
I really appreciate your help! Thanks!

Antworten (3)

dpb
dpb am 24 Jul. 2014
Sure it works, just write d(i,j,k)
But, since Matlab doesn't allow for starting arrays with lower indices other than 1, you'll have two empty planes and a column of zeros besides the actual numeric values.
The Matlab way would be
[x1,x2,x3] = ndgrid(1:10, 2:30, 3:50);
d=5.*x1.*x2./*x3;
The '5' is 10*20/40 in a consolidation of the constants.
doc ndgrid % for the details

Azzi Abdelmalek
Azzi Abdelmalek am 24 Jul. 2014
[a,b,c,d]=deal(zeros(10*29*48,1));
p=0;
for i = 1:10
for j = 2:30
for k = 3:50
p=p+1;
a(p) = 10*i;
b(p) = 20*j*i;
c(p) = 40*k;
d(p) = a(p)*b(p)/c(p);
end
end
end

Sari Mira
Sari Mira am 25 Jul. 2014
Thank you both for your help!
Azzi, unfortunately, the code you sent me ended up making an infinite loop. I tried just running exactly the code you sent, but I just got the infinite loop.
dpb, I'll try that because what I am trying to do is to create a mesh grid with the resulted data.
  1 Kommentar
dpb
dpb am 26 Jul. 2014
_...Azzi, ... the code you sent me ended up making an infinite loop...
??? It (presuming you mean the posted code) is simply three counted loops. Simply impossible to be an infinite loop.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by