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?

 Akzeptierte Antwort

Stephen23
Stephen23 am 8 Okt. 2015
Bearbeitet: Stephen23 am 8 Okt. 2015
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 Kommentare

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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by