splitting output of a loop into multiple parts
4 views (last 30 days)
Show older comments
tjerk Verweij
on 29 Sep 2023
Commented: Dyuman Joshi
on 29 Sep 2023
Hello!
Im new to programming, but i need to do it a bit for my work. yesterday someone already helped me with importing multiple files with a loop. now i have the following problem.
p=0;
for b=1:30
T=A{1,b}.data;
for i=1:length(T(:,1))-1
p=p+1;
R2=T(:,1);
R1=T(:,9);
R(:,p)=(R1(i)*(R2(i+1)-R2(i))+R1(i+1)*(R2(i+1)-R2(i)))/2;
%plot(T(:,[1]),T(:,[9]))
end
Q=sum(R);
end
This is de code i have written to far. I have 30 documents imported (b:1:30) and want to put them all trough a calculation, R. the problem i have currently is that all the calculated values all get into 1 array, instead of a separate array for every document, so basically 30 different ones. I have tried multiple things yesterday but couldnt figure out how to do it.
Hopefully someone here can help me out, if feels like there should be an easy fix for this problem.
Thanks in advance!
0 Comments
Accepted Answer
Dyuman Joshi
on 29 Sep 2023
Dynamically growing arrays is not a good coding practice.
Instead, Preallocate a cell array and vectorize the inner for lop.
p=0;
%As it is not known if the number of rows of T is same for all values of b
%Therefore a cell array is chosen for preallocation
R = cell(1,30);
for b=1:30
T=A{1,b}.data;
i=1:size(T,1)-1;
R2=T(i,1);
R1=T(i,9);
%Use element-wise operations for vectorization
vec=(R1(i).*(R2(i+1)-R2(i))+R1(i+1).*(R2(i+1)-R2(i)))/2;
Q(b)=sum(vec);
R{b}=vec;
end
You can preallocate Q as well. If the number of rows of T is same for all values of b, then prealloace a zeros array for R.
It would be better if you could attach the data you are working with.
2 Comments
More Answers (1)
Katy
on 29 Sep 2023
Hey tjerk,
Let me know if this addresses your question. Hopefully "R" ends up being a 30x1 cell array, with each cell containing the results of the R calculation for each document.
Let me know if you get any errors or this doesn't work.
p=0;
for b=1:30
T=A{1,b}.data;
for i=1:length(T(:,1))-1
p=p+1;
R2=T(:,1);
R1=T(:,9);
%R(:,p)=(R1(i)*(R2(i+1)-R2(i))+R1(i+1)*(R2(i+1)-R2(i)))/2;
R{b,1} = [R{b,1} (R1(i)*(R2(i+1)-R2(i))+R1(i+1)*(R2(i+1)-R2(i)))/2];
%plot(T(:,[1]),T(:,[9]))
end
Q=sum(R);
end
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!