Create cell array of column indices of a specific string

Hi,
I have a 5x1 cell array ,g, where each cell is 40x50. I want to find the column indices of the string 'Latitude' in each of the cells in the cell array. I know there is 7 occurences of this string in each of the cells but I want the code to tell me that. My desired output is a new cell array where each cell contains the column indices of this string (so it will end up being a 5x1 cell array where each cell contains the 7 column indices). I tried this:
ind=find(~cellfun('Latitudes', g));
but it won't work. Any suggestions would be much appreciated
Thank you

 Réponse acceptée

% make cell array g
g = repmat({repmat({''},40,50)},5,1);
% put 7 random 'Latitude's in each cell
for ii = 1:5
g{ii}(randi(2000,7,1)) = {'Latitude'};
end
% get the column index of each instance of 'Latitude'
cidx = cellfun(@get_latitude_columns,g,'UniformOutput',false)
cidx = 5×1 cell array
{7×1 double} {7×1 double} {7×1 double} {7×1 double} {7×1 double}
% put them together in a matrix, if you prefer
% (5x7 or 7x5, whatever makes sense to you)
cidx = [cidx{:}].'
cidx = 5×7
2 3 19 20 30 48 50 8 8 10 11 25 36 46 10 28 29 29 31 32 42 14 16 17 22 34 43 45 2 19 21 25 36 39 50
function idx = get_latitude_columns(s)
[~,idx] = find(strcmp(s,'Latitude'));
end

6 commentaires

Hi,
thank you so much for your reply. Did you mean to write 'g' instead of 's' in the function? & did you have to write your function in a separate script?
Hi, You're welcome!
I meant 's'. I could've called it any valid variable name, as long as it's the same name used on the next line - that's what matters.
I didn't have to use a function, but it was convenient to do so.
Ah, I see! was your function intended to be written at the end of your script? (sorry, MATLAB newb here :') )
Yes, at the end of the script.
The function could also have been in its own m-file, called "get_latitude_columns.m".
Thank you so much, it worked!!
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2021b

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by