How can I store vectors from three loops?
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(3 个)
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
0 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!