Call on function that takes in 2 variables multiple times
12 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
更多回答(1 个)
William Rose
2022-11-10
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!