Cell array as input for loop

조회 수: 20 (최근 30일)
Smoothie Oeek
Smoothie Oeek 2014년 9월 8일
편집: per isakson 2014년 9월 9일
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
Smoothie Oeek
Smoothie Oeek 2014년 9월 8일
My problem here is i dont know how to loop the length of the array. Any help on that?
Image Analyst
Image Analyst 2014년 9월 9일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

per isakson
per isakson 2014년 9월 8일
편집: per isakson 2014년 9월 9일
"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
Smoothie Oeek
Smoothie Oeek 2014년 9월 9일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by