Call on function that takes in 2 variables multiple times

7 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:
N=100
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, :))
end
is there a way to not use a for loop? but still call the function individually and collect it's output into rows?

Accepted Answer

Matt J
Matt J on 10 Nov 2022
Edited: Matt J on 10 Nov 2022
You can hide the loop with arrayfun, but it won't speed things up.
output_vectors = cell2mat(arrayfun(@(i) {example_func(input_doubles(i), input_vectors(i, :)},...
(1:length(input_doubles))' );

More Answers (1)

William Rose
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.
z=x.*v;
end
>> disp(example_func(2,[4,5,6]))
8 10 12
>> disp(example_func([2;4;6;8],[1,2,3;10,20,30;100,200,300;1000,2000,3000]))
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!