Reputation: 223
Some time ago I asked this question: Automatic split of character matrix according to a column values into variable number of new dataframes
For that question the function split
was the perfect answer, now, I am triying to do the same in Matlab and cannot find any function that does the same.
So, its simple, my question is: Is there any function that does the same as the R split
function in Matlab? and if not, how could I do exactly what was asked in the linked question in Matlab?
Upvotes: 1
Views: 4384
Reputation: 2187
I think that what you need is the new table class R2013b:
>> x = {'Hi', 'Med', 'Hi', 'Low'; 'A', 'D', 'A', 'C'; '8', '3', '9', '9'; '1', '1', '1', '2'}';
>> t = cell2table(x)
t =
x1 x2 x3 x4
_____ ___ ___ ___
'Hi' 'A' '8' '1'
'Med' 'D' '3' '1'
'Hi' 'A' '9' '1'
'Low' 'C' '9' '2'
>> slice = t(strcmp(t.x2,'A'),:)
slice =
x1 x2 x3 x4
____ ___ ___ ___
'Hi' 'A' '8' '1'
'Hi' 'A' '9' '1'
>>
For more information, take a look at the table class here
If you'd like to do this for all unique values of the table you can leverage cellfun:
>> slices = cellfun(@(value) t(strcmp(t.x2,value),:), unique(t.x2),'UniformOutput',false)
slices =
[2x4 table]
[1x4 table]
[1x4 table]
>> slices{:}
ans =
x1 x2 x3 x4
____ ___ ___ ___
'Hi' 'A' '8' '1'
'Hi' 'A' '9' '1'
ans =
x1 x2 x3 x4
_____ ___ ___ ___
'Low' 'C' '9' '2'
ans =
x1 x2 x3 x4
_____ ___ ___ ___
'Med' 'D' '3' '1'
>>
In this case you are passing every unique element of t.x2 into this function. Uniform output must be false so that cellfun does not try to concatenate the tables together but rather puts each slice of the table into its own cell.
Upvotes: 1
Reputation: 879
The unique
and strcmp
functions works on cell arrays. What about something like
x = {'Hi', 'Med', 'Hi', 'Low'; 'A', 'D', 'A', 'C'; '8', '3', '9', '9'; '1', '1', '1', '2'}';
for ii = unique(x(:, 3))'
x(find(strcmp(x(:, 3), ii)), :)
end
While it may seems silly, the index array for the for loop must be a row so in unique(x(:, 3))'
the transpose operator is critical. If done correctly ii
is a scalar. Otherwise you will get the error
Error using strcmp Inputs must be the same size or either one can be a scalar
Upvotes: 1