How do I store data from a loop into a matrix or vector?

Hi guys, I'm trying to save values from a loop into a matrix, but my code keeps overwrite the data from the loop.
subplot(2,2,1)
cl={'b.-','k.-','r.-','g.-','c.-','m.-','k.-','g.-','k.-'};
rw=reshape(Rw(sp,hd,:)*L/(rho*g*B^2),[nfr,1]);
nl=reshape(lambda(sp,hd,:),[nfr,1])/L;
plot(nl,rw,cl{hd}); hold on;
grid on;
title(['Added Resistance for ' num2str(u),' knots forward speed for 5 D.O.F '],'FontSize', 18)
ylabel('{R_{aw} \cdot L / \rho g B^2}','FontSize', 18)
xlabel('\lambda / L','FontSize', 18)
xlim([0 1.5])
speed=num2str(u(sp)); heading=num2str(uh(sp,hd)*180/pi);
for i = 1:hd
legendInfo{i} = ['Heading = ' num2str(uh(sp,i)*180/pi)]; % or whatever is appropriate
end
legend(legendInfo)
for pp = 1:hd
rwfff(:,pp) = rw(:,1)
end
The rw is a 20x1 matrix and it runs for each hd, hd is 7. So I need to save each rw values into rwfff so rwfff is a 20x7 matrix. Hope it is understandable.
Thanks in advance
Isa Duran

1 Commento

rw=reshape(Rw(sp,hd,:)*L/(rho*g*B^2),[nfr,1]);
...
for pp = 1:hd
rwfff(:,pp) = rw(:,1)
end
There's nowhere that rw is apparently dependent upon anything excepting coming from an array Rw and the indices to it aren't shown.
But, given that it is a column vector of some value based on those unknown values, there doesn't appear any reason that rwfff woudn't be an array of size(length(rw),hd) when the loop is finished.
It would be more efficient to preallocate rwfff with
rwfff=zeros(length(rw),hd);
before starting the loop but for such a small array it won't be noticeable but in the slightest. For large arrays neglecting this can become a severe bottleneck.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 22 Lug 2015

Commentato:

dpb
il 22 Lug 2015

Community Treasure Hunt

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

Start Hunting!

Translated by