Store Data in Cell-Array

1 visualizzazione (ultimi 30 giorni)
Timo
Timo il 18 Giu 2017
Modificato: Stephen23 il 18 Giu 2017
Hello everybody,
I have a matrix with 1 row of data like you can see below and wanted to extract each block of numbers which always end before the word test, into a seperate field of a cell array. The amount of numbers can vary and after the word test are always following 5 lines of different characters.
C2=
  1. test
  2. a
  3. z
  4. a
  5. r
  6. c
  7. 1
  8. 2
  9. 3
  10. 4
  11. ...
  12. test
  13. a
  14. d
  15. f
  16. a
  17. t
  18. 45
  19. 36
  20. ...
Now I wanted to extract each block of numbers with the following code into a cell array
for i=1:length(C2)
if strcmp(C2{i,1},'Test')
g=g+1;
Cneu{g,1}=i;
end
end
lCneu=length(Cneu)
Data={}
for t=1:lCneu-1
for i=Cneu{t,1}+5:Cneu{t+1,1}-1
g=g+1
Data{t,1}{g,1}=C2{i,1};
end
end
g=0
length_C=length(C2);
for t = lCneu
for i=Cneu{t,1}+5:length_C
g=g+1
Data{t,1}{g,1}=C2{i,1};
end
end
The code stores the data in the cell array but after the first block of data the following blocks aren't stored in the first line of its cell array but in the same line where it was stored in the C2 array.
How can I get each block starting in the first line of its corresponding cell array field?
Thanks in advance
Greetings
  1 Commento
Stephen23
Stephen23 il 18 Giu 2017
Modificato: Stephen23 il 18 Giu 2017
@Timo Schaffhauser: this is not twitter. Please do not write twitter-style tags. (I just edited these for you).

Accedi per commentare.

Risposte (1)

Andrei Bobrov
Andrei Bobrov il 18 Giu 2017
variant for MATLAB R2016b and later
out = num2cell(C2(find(strcmp(C2,'test')) + (1:5)),2)
MATLAB R2016a and earlier:
out = num2cell(C2(bsxfun(@plus,find(strcmp(C2,'test')),1:5),2)
  1 Commento
Timo
Timo il 18 Giu 2017
Thanks for your fast respond :)! Could the problem be (I forgot to mention in the description, sorry about that!) that my C2 is also a cell array, so it can't work? I get the error Index exceeds matrix dimensions (I have to use the second expression you wrote)
Greetings

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by