How to store cell array values from a for loop into another array/matrix?

Hi,
I am trying to store my output values from my for loop into another cell array/matrix. So far this is my code:
fileID = fopen('sample.txt');
C = textscan(fileID,'%s');
for n = 0:5
s = C{1}{(3+8*n)}
end
As you can see, im trying to store every 3 +8n th term from a txt file into an array and im not quite sure how to do this for a cell array. Is there any method on how to do this?

 채택된 답변

Stephen23
Stephen23 2015년 10월 8일
편집: Stephen23 2015년 10월 8일
You don't need to use a loop, just use indexing:
newmat = C{1}(3:8:end);
Of course you can adjust the end term to limit the number of elements, if you need to:
newmat = C{1}(3:8:43);
And this can easily be adjusted to pick rows (or columns):
newmat = C{1}(3:8:end,:);
Basic array indexing is covered in MATLAB's introductory tutorials:

댓글 수: 5

thanks so much much! can't believe this method didnt occur to me
one more question. is it possible to add these values together? i keep on getting the error 'Undefined operator '+' for input arguments of type 'cell'.'
Sorry, what i meant was say for example I have two arrays that had every 2nd and every 4th term. How could i add these two arrays together?
Well, to add two arrays of the same size you use +. However, if you get the error message given, it's because you're adding cell arrays not plain arrays.
If you're wanting to add the content of two cell arrays together it may be:
cellfun(@plus, cellarray1, cellarray2, 'UniformOutput', false)
or something else, depending on what the content of the cell arrays are and the result you expect. As it does not appear to be related to your original question, you should start a new question.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2015년 10월 8일

편집:

2015년 10월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by