How can I store vectors from three loops?

1 view (last 30 days)
Sari Mira
Sari Mira on 24 Jul 2014
Commented: dpb on 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!

Answers (3)

dpb
dpb on 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 on 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 on 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 Comment
dpb
dpb on 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.

Sign in to comment.

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!