Reputation: 11
i have a problem, i'm working on a matlab function which should give out a unknown number of matrix. the problem is that i dont know how i can store them, i need a structure like [A,B,C]
where every entry can be a different matrix, with different size.
how to make this?
Upvotes: 0
Views: 95
Reputation: 5251
Use varargout
.
See http://www.mathworks.co.uk/help/techdoc/matlab_prog/bresuxt-1.html and http://www.mathworks.co.uk/help/techdoc/ref/varargout.html.
Upvotes: 0
Reputation: 124563
Consider the following function, it returns different numbers of outputs depending on the input arguments:
function varargout = myFunc(num)
for i=1:num
varargout{i} = rand(i+2,i);
end
end
Now to call such function and receive all its output, try the following:
num = 5;
X = cell(num,1);
[X{1:num}] = myFunc(num); %# [A,B,C,D,E] = myFunc(5)
the result:
>> X
X =
[3x1 double]
[4x2 double]
[5x3 double]
[6x4 double]
[7x5 double]
Individual matrices can be accessed with cell-array notation:
>> X{5}
ans =
0.75493 0.68342 0.19705 0.80851 0.67126
0.24279 0.70405 0.82172 0.75508 0.43864
0.4424 0.44231 0.42992 0.3774 0.8335
0.6878 0.019578 0.88777 0.21602 0.76885
0.35923 0.33086 0.39118 0.79041 0.16725
0.73634 0.42431 0.76911 0.9493 0.86198
0.39471 0.27027 0.39679 0.32757 0.98987
Upvotes: 3
Reputation: 42225
You need a cell array. Consider this:
A = {[1,2,3;4,5,6],rand(20,'single'), 'hello world'}
A =
[2x3 double] [20x20 single] 'hello world'
A
is a cell container that holds different types of data and different matrix sizes. To index particular "cells", use parenthesis like so:
A(1:2)
ans =
[2x3 double] [20x20 single]
Indexing any array with parenthesis will always return the same data type as that of the array. So here you get two cell arrays. To access the contents of a cell, you use braces, instead of parenthesis. E.g.,
A{1}
ans =
1 2 3
4 5 6
To index inside a cell, use parenthesis along with braces like so:
A{1}(2,1:2)
ans =
4 5
You can read more about cell arrays, their uses and indexing at the Mathworks blog.
Upvotes: 1