Borrar filtros
Borrar filtros

How to iterate through cell array of doubles

8 visualizaciones (últimos 30 días)
Yesbol
Yesbol el 4 de Jul. de 2018
Respondida: Guillaume el 4 de Jul. de 2018
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

Respuestas (1)

Guillaume
Guillaume el 4 de Jul. de 2018
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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by