cell of string. Vectorization on elements of string

G'Day
I have as an input the cell stringCell, and I try to access to the element indexToAcces of each stringCell element. In this example indexToAcces is the same for all, but in my main code indexToAcces would be the same size of stringCell and each value could be different:
stringCell{1,1}='test1'
stringCell{2,1}='test2'
indexToAcces=5
stringCell{1,1}(indexToAcces) %returns 1; this work for one element
stringCell{:,1}(indexToAcces) %this does not work,why? ??? Bad cell reference operation.I would like it to return a cell array of :'1','2'
%%So I have to do it this way but this is not efficient at all when
%%there are many elements
for ii=1:length(stringCell)
getNum{ii}=stringCell{ii,1}(5); %works
end
I always had this issue, but used not to bother too much since the size of my cells was not too big. Unfortunately, It is not the case anymore, and my code is not efficient anymore. I spend hours trying to find a solution (forums ...). So I would be really grateful if someone has an answer.
Cheers Laurent

 Akzeptierte Antwort

Wayne King
Wayne King am 22 Mai 2012
stringCell{1,1}='test1' ;
stringCell{2,1}='test2';
out = cellfun(@(x) x(5),stringCell,'UniformOutput',0);
out = str2num(char(out));

1 Kommentar

Laurent
Laurent am 22 Mai 2012
Thanks a lot ! I can even replace 5 by a matrix. I use quite often cellfun, but never really used those @(x), have to check this out.
Many thanks

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 22 Mai 2012
stringCell{:,1}(indexToAcces) % ??? Bad cell reference operation
"string{:,1}" is a comma separated list, which cannot be indexed.
I assume that this is faster than the CELLFUN(@(x)) approach:
getNum = cell(1, length(stringCell)); % Pre-allocate
for ii=1:length(stringCell)
getNum{ii} = stringCell{ii}(5); % Abbreviation for: stringCell{ii,1}
end

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by