Fill function with multiple variable inputs, being this different length arrays

2 views (last 30 days)
for idx=1:size(struct2table(StructwithVectors),1)
Vector_X=StructwithVectors(idx).Points %here I have 4 matrix with diferent length [1x3],[1x4],[1x2],[1x2];
end
% i wanted to be able to insert this Vector_X into a fuction but without
% hardcoding it
function_test(Vector_X(idx(1)),Vector_X(idx(2).., other inputs);
% I can't colect it as a matrix because they have diferent sizes.

Accepted Answer

Vilém Frynta
Vilém Frynta on 25 Nov 2022
Edited: Vilém Frynta on 25 Nov 2022
I have 2 ideas. They do involve changing your function, just slightly.
(1) Instead of "unpacking" your StructWithVectors into Vector_X, you can just insert the whole StructWithVectors and "unpack" your vectors inside your function. You will need to edit your function to be ready to accept structure.
(2) You need to edit your vectors to have the same length. You will insert some values (prefferably NaNs, zeros or blanks). Then, in your function, you will ignore these values.
Example code for solution (2):
q = [1 3 5 7]; % Short vector
k = [9 6 3 0 -3 -6 -9]; % Longest vector that you have
% After you find your longest vector, you will use it's size
maxSize = length(k);
% You will check length of other vectors and make them same length
smolSize = length(q);
v = NaN(1,maxSize); % Create vector made of NaNs
v(1:smolSize) = q % Assign values of your short vector
v = 1×7
1 3 5 7 NaN NaN NaN
Now, you have 1x7 vector, that contains the same information and has same length as the longest vector. In your function, you can simply ignore NaNs with using isnan.
idx = ~isnan(v); % index of non-NaN values
v = v(idx) % voilá, your short vector again
v = 1×4
1 3 5 7
This was just simple example, you can use for loop accordingly to your needs, to go through all the vectors and automatize this process.
Hope I helped.
Edit: aesthethic, code example, details

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!