how to use "for" loop to save variables to an array?

9 views (last 30 days)
I have a data vector.it has severals positive and negative areas. I have calculated each area one by one using trapz function. is there any way to find this area using loop ?
I have used this for loop, but showing only the last result.attaced the "mat" file here.
loop:
i=0;
for i=1:length(zeroaxes)
time(i:zeroaxes(i))=time(i:zeroaxes(i));
power(i:zeroaxes(i),1)=power(i:zeroaxes(i));
areaone=trapz(time,power);
end
Code(Manually calculated the area using trapz):
A=load('power.mat');
power=A.power;
time=1:length(power);
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Zero-Crossing Indices
zeroaxes = zci(power);
%% Area Calculation
time_1=time(1:zeroaxes(2)); % time of area1 calculation
power_1=power(1:zeroaxes(2)); % power of area1
area_1=trapz(time1,power1); % integrated area1
time_2=time(zeroaxes(2):zeroaxes(3));
power_2=power(zeroaxes(2):zeroaxes(3));
area_2=trapz(time2,power2);
time_3=time(zeroaxes(3):zeroaxes(4));
power_3=power(zeroaxes(3):zeroaxes(4));
area_3=trapz(time3,power3);
time_4=time(zeroaxes(4):zeroaxes(5));
power_4=power(zeroaxes(4):zeroaxes(5));
area_4=trapz(time4,power4);
time_5=time(zeroaxes(5):zeroaxes(6));
power_5=power(zeroaxes(5):zeroaxes(6));
area_5=trapz(time5,power5);

Answers (1)

cr
cr on 14 Dec 2021
Edited: cr on 14 Dec 2021
Of course, it will show the last result only since you are overwriting the areaone variable in every iteration of the loop. You might want to do
areaone(i)= trapz(time,power);
inside the loop.
  1 Comment
Stephen23
Stephen23 on 21 Dec 2021
Tashaf hoq's incorrectly posted "Answer" moved here:
yes, almost like that.
actually in my mat file has 15 areas. Zero-Crossing Indices(zci) has 16 elements.so my data has 15 areas.to avoid bunch of lines i have just provided the code for 5 areas. so want to calculate these 15 areas with loop. everytime doing manually/one by one is time wasting initiation.
could you please light up about the syntax ?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by