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 件のコメント

Chris Charles
Chris Charles 2015 年 10 月 8 日
thanks so much much! can't believe this method didnt occur to me
Chris Charles
Chris Charles 2015 年 10 月 8 日
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'.'
Thorsten
Thorsten 2015 年 10 月 8 日
Cs = cellfun(@sum, C);
Chris Charles
Chris Charles 2015 年 10 月 8 日
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?
Guillaume
Guillaume 2015 年 10 月 8 日
編集済み: Guillaume 2015 年 10 月 8 日
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