for loop to go through a cell array
5 次查看(过去 30 天)
显示 更早的评论
I have written a code which tells me how many particles go past a certain x-coordinate for a single time step. The code accesses one cell of a 710x1 cell array currently, but now I want to tell it to do this for all the cells in the array, so i can plot a particles vs. time graph.
I know I need another for loop to do this, but I am unsure how to tell it to go through all the cells in the array.
%% particles leaving the rice pile
%for each cell in the array (timestep), calculate the number of particles after a certain x coordinate
%access the {nth} cell of the cell array, and save all the rows in the 5th column (x-coordinates) as a new variable
xc = particledata{212}(:,5);
%use the function table2array to turn the format of the data from a table to an array
xc_array = table2array(xc);
%for all the rows in the array, if the x coordinate goes beyond the outlet
%of the rice pile, display 'grain left rice pile'
%-0.15 is the x coordinate for the outlet
ricepileoutlet = -0.15
for b = 1:size(xc_array,1)
if xc_array(b,1)< ricepileoutlet
disp('grain left rice pile')
end
end
%display how many grains in total left the rice pile in the time step
%add up the number of times the x coordinate is >0.188 and save this in a new variable 'grains'
grains=sum(xc_array(:,1)< ricepileoutlet);
fprintf('A total of %d grains left the rice pile\n',grains);
0 个评论
回答(1 个)
KALYAN ACHARJYA
2020-11-25
编辑:KALYAN ACHARJYA
2020-11-25
No loop needed here
% FOllowing result counts the total grain left rice pile
result=sum(xc_array>ricepileoutlet)
Note: Assumed that xc_array is an 1D array
7 个评论
KALYAN ACHARJYA
2020-11-25
Have you tried this example?
grain_num=zeros(1,size(xc_array,1));
for i=1:size(xc_array,1)
data=xc_array{i};
grain_num(i)=sum(data>ricepileoutlet);
end
bar(grain_num);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!