Clear Filters
Clear Filters

Function input vector specifiers

3 views (last 30 days)
Jay
Jay on 1 Oct 2020
Answered: Ameer Hamza on 1 Oct 2020
Is there a way to specify all elliments of a vector in a functions input term?
ie. instead of writing
val_1 = mat_val(1,1)
val_2 = mat_val(1,2)
val_3 = mat_val(1,3)
val_4 = mat_val(1,4)
function [ret_val] = filename (val_1, val_2, val_3 , val_4)
ret_val = val_1*val_3 - val_4 + val_2
end
I can have a specifer with the correct syntax to match
function [ret_val] = filename(mat_val(1,:))
ret_val = val_1*val_3 - val_4 + val_2
end
The functions return will be called in a seperate script file.
Thanks

Answers (1)

Ameer Hamza
Ameer Hamza on 1 Oct 2020
It is always a good idea to use an array instead of separate variable names: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. However, the following shows a somewhat acceptable way
function [ret_val] = filename(varargin)
[val_1, val_2, val_3, val_4] = varargin{:};
ret_val = val_1*val_3 - val_4 + val_2;
end
Call it like this
y = filename(1, 2, 3, 4)

Categories

Find more on Programmatic Model Editing in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!