Storing multiple function outputs in an iterative loop

14 views (last 30 days)
I have multiple variables (of different lengths) (input_1; input_2; etc ..input_i) and for each of them I would like to run my function that takes input_1 and returns output X_1, Y_1, Z_1 and saves it to the workspace (and then respectively taking input_i and returing X_i, Y_i, Z_i).
The input and output variables have different lengths for each index (i.e. input1 is different size than input2), so they can’t be stored in one matrix.
I tired running a for loop, but I don’t know how to save the output_i iteratively as separate variables (as they have different lengths) for each input_i in the function.
[X,Y,Z] = myfunction(input_variable);
%the function takes a 3d matrix and creates three 1d output vectors X, Y and Z of different lengths
%sample data (different size)
input_1=rand(100,4,3);
input_2=rand(50,3,1);
input_3=rand(10,2,5);
index_name = {'1', '2', 3};
for i=1:length(index_name)
AA = sprintf(input_%s’,index_name{i});
input_variable = eval(AA);
[X,Y,Z] = myfunction(input_variable);
%here I am not sure how to save output vectors Xi, Yi, Zi for each iteration, as the following code does not work:
outputX = sprintf(X_%s’,index_name{i});
eval([ outputX ' = X’ ]);
end
Please note that output vectors for each iteration have different lengths and can’t be saved in a matrix (i.e. outputs X_1, X_2, X_i has different lengths). I would really appreciate if somebody could tell me how to save them into workspace.

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 1 Oct 2014
Edited: Mohammad Abouali on 1 Oct 2014
store them as cell arrays
[X{i},Y{i},Z{i}] = myfunction(input_variable);
x{1} could be NxM matrix
X{2} could be RxCxT matrix
X{3} could be even a string
So, really doesn't matter what are each element of cell arrays. They are independent of each other

More Answers (0)

Categories

Find more on Language Fundamentals 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!