45 lines
1.1 KiB
Matlab
45 lines
1.1 KiB
Matlab
clear
|
|
|
|
% cell arrays are like n-dimensional arrays, but have hetergeneous
|
|
% data-types inside
|
|
|
|
a = {'p'};
|
|
v = {1 'a'};
|
|
D = {1 2; 't' [1 2]};
|
|
|
|
% like vectors, scalars, and matrices, cell arrays are two-dimensional
|
|
% by default
|
|
assert(ndims(a) == 2);
|
|
assert(ndims(v) == 2);
|
|
assert(ndims(D) == 2);
|
|
|
|
% indexing a cell array follows the same rules, and returns another cell
|
|
% array (like indexing a matrix returns a matrix, remember that scalar
|
|
% are 1x1 matrices
|
|
assert(all(size(D(2, 2)) == [1 1]));
|
|
|
|
% to unbox the cell values, index with {} instead of ()
|
|
% this will return a matrix instead of a cell
|
|
assert(D{2,1} == 't');
|
|
assert(all(D{2, 2} == [1 2]));
|
|
|
|
% equality check:
|
|
cs = {1+3 2};
|
|
assert(isequal(cs, {4 2}));
|
|
|
|
% convert cell array to standard array
|
|
assert(isequal(cell2mat(cs), [4 2]));
|
|
|
|
% arrayfun can output a non uniform cell array
|
|
struct_array(1).data = [1 2];
|
|
struct_array(2).data = [1 2 3];
|
|
|
|
try
|
|
arrayfun(@(x) x.data, struct_array)
|
|
catch e
|
|
assert(isequal(e.identifier, 'MATLAB:arrayfun:NotAScalarOutput'));
|
|
end
|
|
|
|
assert(isequal( ...
|
|
arrayfun(@(x) x.data, struct_array, 'UniformOutput', false), ...
|
|
{[1 2], [1 2 3]})); |