splitting output of a loop into multiple parts
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
tjerk Verweij
le 29 Sep 2023
Commenté : Dyuman Joshi
le 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 commentaires
Réponse acceptée
Dyuman Joshi
le 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 commentaires
Plus de réponses (1)
Katy
le 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
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!