Azzera filtri
Azzera filtri

Need help with a nested for loop

3 visualizzazioni (ultimi 30 giorni)
Joel Coburn
Joel Coburn il 30 Mag 2015
Commentato: Image Analyst il 30 Mag 2015
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.

Risposta accettata

Image Analyst
Image Analyst il 30 Mag 2015
Modificato: Image Analyst il 30 Mag 2015
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 Commenti
Joel Coburn
Joel Coburn il 30 Mag 2015
Worked perfectly! Thanks so much
Image Analyst
Image Analyst il 30 Mag 2015
Just curious - which version did you use?

Accedi per commentare.

Più risposte (2)

Murali Krishna
Murali Krishna il 30 Mag 2015
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 il 30 Mag 2015
t = ((pi*((D+0.064).^2)/4)-(pi*D.^2)/4);
V = bsxfun(@times, L, t.');

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by