Need help with a nested for loop

3 次查看(过去 30 天)
I have
L = 28x1 vector
D = 28x1 vector
My equation is: V = L*((pi*((D+0.064).^2)/4)-(pi*D.^2)/4)
I have tried
for n = 1:length(D1)
for m = 1:length(L1)
TankVol(n,m) = L1(m,:)*((pi*((D1(n,:)+0.064).^2)/4)-(pi*D1(n,:).^2)/4);
end
end
But it's not giving what I need
It's going through the loop too many times if that makes sense, I basically need a V value for each value in L and D.

采纳的回答

Image Analyst
Image Analyst 2015-5-30
编辑:Image Analyst 2015-5-30
If there is a value of D1 for every value of L1 and vice versa, what about:
L1 = rand(28, 1); % 28x1 vector
D1 = rand(28, 1); % 28x1 vector
% My equation is: V = L*((pi*((D+0.064).^2)/4)-(pi*D.^2)/4)
for n = 1:length(D1)
for m = 1:length(L1)
TankVol(n,m) = L1(m)*((pi*((D1(n)+0.064).^2)/4)-(pi*D1(n).^2)/4);
end
end
imshow(TankVol, []);
Or, if you want to take the nth element of D1 at the same time that you take the nth element of L1:
L1 = rand(28, 1); % 28x1 vector
D1 = rand(28, 1); % 28x1 vector
% My equation is: V = L*((pi*((D+0.064).^2)/4)-(pi*D.^2)/4)
TankVol = L1 .* ((pi*((D1+0.064) .^ 2)/4)-(pi*D1 .^ 2)/4);
plot(TankVol, 'b*-');
grid on;

更多回答(2 个)

Murali Krishna
Murali Krishna 2015-5-30
In matlab u need not use loop to access each element. Try this
V = L.*((pi*((D+0.064).^2)/4)-(pi*D.^2)/4)
result will be stored in v as column matrix

Walter Roberson
Walter Roberson 2015-5-30
t = ((pi*((D+0.064).^2)/4)-(pi*D.^2)/4);
V = bsxfun(@times, L, t.');

类别

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