Cell array as input for loop

27 views (last 30 days)
Smoothie Oeek
Smoothie Oeek on 8 Sep 2014
Edited: per isakson on 9 Sep 2014
So the input is a 1D Cell array. So im wishing to pass each element of the Cell Array into a function one by one. And that should give me 2 values. And then i need to put these into a 2D array, each row being the 2 values of one element. So i should have a 200x2 2D array. I used a for loop for that, but im not sure how to loop through the whole array of elements?
ExtractElement = Element{1};
ElementAverage = zeros(200,2);
for i = 1:length(Element)
[A,B] = AverageElement('ExtractElement'); %This is the function
ElementAverage(i,:) = [A,B];
end
end
Then im stuck
  3 Comments
Smoothie Oeek
Smoothie Oeek on 8 Sep 2014
My problem here is i dont know how to loop the length of the array. Any help on that?
Image Analyst
Image Analyst on 9 Sep 2014
I don't understand why you're using cell arrays at all instead of normal numerical arrays. And Element is a 200 row by 1 column array of cells - okay fine. But why is ExtractElement equal to the contents of the first cell, and why are you passing the literal string 'ExtractElement' (which has absolutely nothing to do with the variable ExtractElement) into your function? Even if you were to pass the contents of the ith cell into AverageElement(), what ARE the contents of that cell, and why does averaging it produce two output values? Basically the question does not make sense.
I think you would benefit greatly by reading the FAQ on cell arrays to understand what they are and how they work: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F

Sign in to comment.

Answers (1)

per isakson
per isakson on 8 Sep 2014
Edited: per isakson on 9 Sep 2014
"problem here is I don't know how to loop [over] the length of the array"
Hint:
cac = {'a','b','c'};
% loop over all columns
for c = cac
disp(c{:})
end
displays
a
b
c
&nbsp
"But i want to store the values each time. how would i do that?" displays
Hints:
>> cssm
ans =
'a' [97]
'b' [98]
'c' [99]
where
function out = cssm
cac = {'a','b','c'};
out = cell( length(cac), 2 );
for jj = 1 : length( cac )
[ out{jj,:} ] = one2two( cac(jj) );
end
end
function [ str, num ] = one2two( c )
str = c{:};
num = double( str );
end
&nbsp
and
>> cssm
ans =
97 9409
98 9604
99 9801
where
function out = cssm
cac = {'a','b','c'};
out = zeros( length(cac), 2 );
for jj = 1 : length( cac )
out(jj,:) = one2two( cac(jj) );
end
end
function n = one2two( c )
n = double( c{:} );
n = cat( 1, n, n*n );
end
  1 Comment
Smoothie Oeek
Smoothie Oeek on 9 Sep 2014
Yup so i did that thanks! But now since the values inside the loop keeps changing. But i want to store the values each time. how would i do that?

Sign in to comment.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!