필터 지우기
필터 지우기

How to iterate through cell array of doubles

조회 수: 8 (최근 30일)
Yesbol
Yesbol 2018년 7월 4일
답변: Guillaume 2018년 7월 4일
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

답변 (1개)

Guillaume
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by