how do I find the type of a value inside a cell array?
Show older comments
I need to load only one variable from a mat file. this variable is a cell array that contains a string and a scalar. but I don't know in which order (the first place in the cell array can be a scalar or a string) how can I find which one of them is the string maybe using find? thanks
a code for example:
% code
load('Myfavoritefile.mat','myFavoriteVar')
myFavoriteVar ={'ExampleString' 5}
% or {5 'ExampleString'} I don't know but I only need the string
%the string is the name of the xl file I want to open
[NUMERIC,TXT,RAW]=xlsread(ExampleString)
Accepted Answer
More Answers (1)
Simply test the type of the first cell element:
myFavoriteVar = load('Myfavoritefile.mat','myFavoriteVar')
if ischar(myFavoriteVar{1})
ExampleString = myFavoriteVar{1};
ExampleData = myFavoriteVar{2};
else
ExampleString = myFavoriteVar{2};
ExampleData = myFavoriteVar{1};
end
[NUMERIC,TXT,RAW]=xlsread(ExampleString);
8 Comments
ilona
on 28 Dec 2013
Image Analyst
on 28 Dec 2013
I was confused too. The only thing I could think of was that myFavoriteVar is an array where each row has another number and another filename - but that's just a guess.
Christopher
on 9 Aug 2018
I suppose you could use cellfun to avoid writing the loop as an academic exercise. I'm not sure it would buy you anything in terms of execution time though.
Loup&Snoop
on 20 Aug 2019
cellfun is definitely the desired solution. I'm also trying to write it without a loop, mostly to keep code tidy (yes, I'm that vain). Here is an example for this question:
strcmp(cellfun(@class,MYCELLARRAY,'UniformOutput',false),'char')
Peter Perkins
on 30 Aug 2019
Edited: Peter Perkins
on 30 Aug 2019
>> c = {1 'abc'};
>> cellfun(@ischar,c)
ans =
1×2 logical array
0 1
Or perhaps
>> find(cellfun(@ischar,c))
ans =
2
Also, don't use xlsread unless you have a good reason to. Use readtable, or maybe readmatrix (in recent versions).
Jesús Julián de Niz Hernández
on 12 Feb 2021
@Peter Perkins hi, why did you use the @ before the ischar? thanks
Image Analyst
on 12 Feb 2021
Edited: Image Analyst
on 12 Feb 2021
Julian, the @ tells it that ischar is the name of a function and not to try to evaluate (run) ischar right then and there.
Otherwise it WILL try to run it and since you don't have any argument being passed to it within parentheses, it will say that you didn't supply any arguments to ischar(), like this:
>> find(cellfun(ischar,c))
Error using ischar
Not enough input arguments.
See, it basically tried to do this
ischar()
and take the result, along with the cell array called c, and pass them to the cellfun() function as inputs. But ischar() with no arguments is not allowed, so it throws an error. Does that explain it?
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!