How to iterate through cell array of doubles
5 次查看(过去 30 天)
显示 更早的评论
Hi all,
Let's say, I have a 1x7 cell
for i = 1:7
num{i}=rand(randi(20),1);
end
Now I want to find sum of each element in a cell
for i = length(num)
smth(i)=sum(num{1,i})
end
But I only get the sum of the last element
smth =
0 0 0 0 0 0 5.9991
>> sum(num{1,end})
ans =
5.9991
So I can't store the values. Can you guide me on this and explain how looping in cells works?
Thanks
0 个评论
回答(1 个)
Guillaume
2018-7-4
The error is with the syntax of your for which should be:
for i = 1:length(num) %and numel instead of length would be better
Also, since num is a vector, I'd use num{i} instead of num{1, i}. The former works whether num is a row, column or any other direction vector, the later only works with row vectors.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!