Conversion from cell array - matlab

I have a cell array of 150 by 1 . My problem is why cant we use the eq function, as in
the value of species(1) = 'setosa',
but when I write species(1) == 'setosa' I was expecting to get a logical 1 but MATLAB gives Undefined function eq for cell array . I require this because I want to convert it into a logical array . How should I achieve this

You can do this by using find() and strcmp() together.
Example:
stts = {'Gable','Hip','Shed','Shed','Other'}; % string cell array
[truefalse,index]=find(strcmp(stts,'Shed')) % do it here if you want to find `Shed`
After this, truefalse are the logical values and index are the according indexes found.
truefalse =
1 1
index =
3 4

Related

How to find all values greater than 0 in a cell array in Matlab

I want to find and save all values greater than 0 in an array and save them in a variable called "times". How do I do that? And what is the difference between saving the indices of those cells versus the actual values of the cells?
This is what I have tried, but it must be worng because I get the error:
Undefined operator '>' for input arguments of type
'cell'.
clear all, close all
[num,txt,raw] = xlsread('test.xlsx');
times = find(raw(:,5)>0)
To access the contents of a cell you must use {} instead of ():
idx = find([raw{:, 5}] > 0);
But this gives you the index of the cells of raw containing a positive value. If you want the values instead, you can access them and collect them in a numeric array in this way:
times = [raw{idx, 5}];

Concatenating (sub)fields of structs in a cell array

I have a Matlab object, that is a cell array containting structs that have almost identical structures and I want to programmatically get a (sub)field of the structs of all cell array elements.
For example, we take test
test = {struct('a',struct('sub',1)), struct('a',struct('sub',2),'b',1)};
This will create a cell array with the following structure:
cell-element 1: a --> sub --> 1
cell-element 2: a --> sub --> 2
\-> b --> 1
It can be seen that the elements of test don't have the exact same structure, but similar. How can I get all values of the a.sub fields of the elements of the cell. I can obtain them in this specific problem with
acc=zeros(1,numel(test));
for ii=1:numel(test)
acc(ii) = test{ii}.a.sub;
end
but I can't quite get this method to work in a more general context (ie. having different fields).
You may want to use the function getfield:
%//Data to play with
test = {struct('a',struct('sub',1)), struct('a',struct('sub',2),'b',1)};
%//I'm interested in these nested fields
nested_fields = {'a', 'sub'};
%//Scan the cell array to retrieve the data array
acca = cellfun(#(x) getfield(x, nested_fields{:}), test);
In case your data cannot guarantee that all the elements are the same type and size, then you need to output a cell array instead:
%//Scan the cell array to retrieve the data cell array
accc = cellfun(#(x) getfield(x, nested_fields{:}), test, 'UniformOutput', false);
Later Edit
If one wants to use different sets of nested fields for each cell element then:
%//nested_fields list should have the same size as test
nested_fields = {{'a','sub'}, {'b'}};
accm = cellfun(#(x,y) getfield(x,y{:}), test, nested_fields, 'UniformOutput', false);
Edit: No need for recursion, as shown by #CST-link:s answer; the native getfield function can neatly unfold a cell array of fields as its second argument, e.g. getfield(foo{i}, fields{:}) instead of the call to the recursive function in my old answer below. I'll leave the recursive solution below, however, as it could have some value in the context of the question.
You can build you own recursive version of getField, taking a cell array of fields.
function value = getFieldRec(S,fields)
if numel(fields) == 1
value = getfield(S, fields{1});
else
S = getfield(S,fields{1})
fields{1} = [];
fields = fields(~cellfun('isempty',fields));
value = getFieldRec(S,fields);
end
end
Example usage:
foo = {struct('a',struct('sub',1)), ...
struct('a',struct('sub',2),'b',3), ...
struct('c',struct('bar',7),'u',5)};
accessFields = {'a.sub', 'b', 'c.bar'};
values = zeros(1,numel(foo));
for i = 1:numel(foo)
fields = strsplit(accessFields{i},'.');
values(i) = getFieldRec(foo{i},fields);
end
With the following result
values =
1 3 7
I have found a way to do this using eval:
function out = catCellStructSubField(cellStruct, fieldName)
out = zeros(1,numel(cellStruct));
for ii = 1:numel(cellStruct)
out(ii) = eval(['cellStruct{ii}.' fieldName]);
end
Where it can be used on my test example like this:
catCellStructSubField(test, 'a.sub')
Dynamic field names (cellStruct{ii}.(fieldName)) does not work because I'm accessing sub-fields.
I know eval is often a bad idea. I'm curious for different solutions.

Correct way of adding to a list from cell array in matlab?

I'm writing some code to split up a 180x2 matlab cell array based on a string in the second column. This string is one of EP,GA,PS,SS or SA. In python I could define empty lists then use conditionals to iterate over the elements of the list and append them to the relevant lists.
The Code
EP=[];
GA=[];
PS=[];
SA=[];
SS=[];
for i=1:size(d),
if strcmp(d(i,2),'EP'),
append(EP,d(i,1))
elseif strcmp(d(i,2),'GA'),
append(GA,i)
elseif strcmp(d(i,2),'PS'),
append(PS,i)
elseif strcmp(d(i,2),'SA'),
append(SA,i)
elseif strcmp(d(i,2),'SS'),
append(SS,i)
end
end
Note that 'd' is a 180x2 cell array that I copied and pasted into matlab rather than import. The general structure of the data however is:
12.9089000000000 'EP'
13.3697000000000 'SA'
13.4335000000000 'EP'
13.5302000000000 'PS'
13.8434000000000 'EP'
14.2583000000000 'EP'
14.8221000000000 'GA'
However when attempting this tactic in matlab I get an error:
Error using append (line 38)
Wrong number of input arguments for obsolete
matrix-based syntax.
Error in Boxplot_All_results (line 12)
append(GA,i)
Could somebody tell me the correct way of doing this in matlab
First of all, please not that d is a cell array. To index the elements of a cell array, use {}. If you index using () like you did, you end up with a small cell array containing only the indexed element(s).
To append in Matlab you basically have two choices:
%concatenate the list with a scalar. Also suitable for two lists.
EP=[EP,d{i,1}] %could also be done using cat
%append to the end
EP(end+1)=d{i,1}
While this fixes the problem, I recommend to implement it on a more generic way:
names={'EP','GA','PS','SA','SS'}
s=struct()
for idx=1:numel(names)
s.(names{idx})=[d{strcmpi(d(:,2),names{idx}),1}]
end
You end up with a struct containing the data you want.
Can you show MatLab code?
How do you append those values to cell array?
You can just create one a = {}
and then append element at the size+1 index. That operation extends your cell array.
Or you can also do a trick like that: a = [a; {value}]
To append elements to a cell array, a correct syntax would be:
for i=1:size(d),
if strcmp(d(i,2),'EP'),
EP = [EP ; d(i,1) ] ; %// append(EP,d(i,1))
elseif strcmp(d(i,2),'GA'),
GA = [GA ; d(i,1) ] ; %// append(GA,i)
but there are more ways, as you can read in the documentation: Add Cells to a Cell Array
There are also more ways to build your final extracted arrays in one assignment instead of having them growing dynamically (mLint will complain about that by the way).
Get the indices of the elements which satisfy your condition then create an array with only the matching elements. For example:
iEP = cellfun( #(c) strcmp(c,'EP') , d(:,2) ) ; %// logical array of indexes where the condition is true
EP = d(iEP,1) ; %// Create "EP" in one assignment - EP is a [cell] array
If you only have numeric values to retrieve in these new variables, may be having a double array instead of a cell array will be convenient :
iGA = cellfun( #(c) strcmp(c,'GA') , d(:,2) ) ; %// logical array of indexes where the condition is true
GA = cell2mat( d(iGA,1) ) ; %// Create "GA" in one assignment - GA is a [double] array
Of course you can bypass the intermediate variable holding the indices:
PS = d( cellfun(#(c)strcmp(c,'PS'),d(:,2)),1) ; %// Create "PS" in one assignment [cell] array
SA = cell2mat(d(cellfun(#(c)strcmp(c,'SA'),d(:,2)),1)) ; %// Create "SA" in one assignment [double] array

Function for comparing two cell arrays

I have a cell array (2000*10) with each cell containing a string such as '25:20:55'.
I want to write a function that accepts 10 inputs (say '25:02:33', '58:69:88', '25:54:96', '48:58:36', '58:54:88' and so on) and looks for a match in each column corresponding to input value for that particular column (i.e. the first input data corresponds to 1st column, 2nd to 2nd column of the stored data and so on.
How can I write a function for the above comparison?
Assuming the cell array contains strings, you can find matches using strcmp:
input = {'25:02:33', '58:69:88', '25:54:96', '48:58:36', '58:54:88'};
match_idx = strcmp(repmat(input, size(cell_data,1),1), cell_data);
If you only want to know if there are matches in the respective columns at all and do not care about the line index of the match, you can do
match = any(match_idx,1);
Use ismember
ismember(your_var, your_cell);
e.g.
c = {'a', 'b', 'c', 'd'};
ismember('b', c)
ans =
1
ismember('q', c)
ans =
0
In your case, something like could work
function arr = myfun(inputvec, inputmat)
for i=1:length(inputvec) %// where inputvec is the cell-vector with the strings you want to search for
arr(i) = ismember(inputvec{i}, inputmat{:,i});
end

extracting the index of a certain character in a cell array

I have a cell array like this:
and I want to extract the index of 2 in this cell array so I used these lines of codes:
for i = 1:size(idx,1)
if idx{i,1} ~= []
index = i;
end
end
but the code doesn't work.I mean the debuger never enters if beacause it doesn't understand that 2 differs from [].why? and how do you suggest me to write the code?
note that the character will not always be 2 and it may occur in other indexes too.
To test if you variable is empty use ISEMPTY function.
To do it for all elements in a cell array you can use CELLFUN:
index = find(~cellfun(#isempty, idx));
In Matlab, [] means empty, thus:
for i = 1:size(idx,1)
if ~isempty(idx{i,1})
index = i;
end
end