Call on function that takes in 2 variables multiple times
2 views (last 30 days)
so my function takes in one double variable and one 1by3 array
it outputs a 1by3 array
I was wondering if theres a way to pass in a N by 1 double, with a N by 3 array, and have it output a N by 3 array without using a loop, my code currently looks like this:
input_doubles = rand(N,1)
input_vectors = rand(N,3)
output_vectors = zeros(length(input_doubles),3);
for i = 1:1:length(input_doubles)
output_vectors = example_func(input_doubles(i), input_vectors(i, :))
is there a way to not use a for loop? but still call the function individually and collect it's output into rows?
More Answers (1)
William Rose on 10 Nov 2022
You can write a funciton that returns values whose size varies as the size of the inputs vary. I am not sure if that is acceptable to you. Here is an example.
function z = example_func(x,v)
%EXAMPLE_FUNC Returns vector or array.
% If size(x)=1x1 and size(v)=1x3, then size(z)=1x3.
% If size(x)=Nx1 and size(v)=Nx3, then size(z)=Nx3.
% See Matlab Answers post by Spacestudent112233, 2022-11-10.
8 10 12
2 4 6
40 80 120
600 1200 1800
8000 16000 24000
If you pass it a double and a vector, it retruns a vector.
Example 1 above: It returns 1x3 when it recieves 1x1 and 1x3.
Example 2, above: N=4. It returns Nx3 when it receives Nx1 and Nx3.
This is what you requested. Good luck.