Cell arrays and the unique function
1 view (last 30 days)
Show older comments
Hi all,
Working on some code to remove cell arrays so I can convert the code to C using Matlab Coder.
Just wondering what the right way of going about it would be for something like this:
myvalues = unique({input_x.(my_name)});
The input is a cell array, so the unique function also returns a cell array, neither of which I want. Any pointers of how to go about this to remove the cell arrays would be appreciated.
Thanks
0 Comments
Accepted Answer
Cedric
on 20 Mar 2013
Edited: Cedric
on 20 Mar 2013
You can proceed as follows:
>> c = {1, 2, 3, 4}
c =
[1] [2] [3] [4]
>> [c{:}]
ans =
1 2 3 4
It is applied to struct arrays as follows:
>> input_x = struct('a', {7,8,9,5,4,3}) ;
>> [input_x.a]
ans =
7 8 9 5 4 3
or, if the fieldname is not static
>> [input_x.('a')]
ans =
7 8 9 5 4 3
In fact, c{:} is a comma-separated list (the same that you have when you define columns of an array, or when you list arguments in function calls), so the outcome of "square-bracketting" it is an array. It is something quite useful when you want to pass elements of a cell array to a function as if you were listing arguments separated by commas. To illustrate..
function myPrintf(format, varargin)
% do something..
fprintf(format, varargin{:}) ;
end
Calling
myPrintf('Name:%s, age:%d, streetNo:%d\n', 'John', 40, 12) ;
leads to varargin = {'John', 40, 12}, and using it as a comma-sep. list with varargin{:} in the call to FPRINTF is indeed performing the following call
fprintf('Name:%s, age:%d, streetNo:%d\n', 'John', 40, 12) ;
.. it's the to some extent the MATLAB way for managing cases where you'd use a vector function in C, e.g. vfprintf ..
0 Comments
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!