How can I store vectors from three loops?

조회 수: 1 (최근 30일)
Sari Mira
Sari Mira 2014년 7월 24일
댓글: dpb 2014년 7월 26일
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!

답변 (3개)

dpb
dpb 2014년 7월 24일
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 2014년 7월 24일
[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 2014년 7월 25일
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
dpb
dpb 2014년 7월 26일
_...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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by