splitting output of a loop into multiple parts
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Dyuman Joshi
2023-9-29
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.
更多回答(1 个)
Katy
2023-9-29
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!