Matlab: store input variables for arrayfun

1 次查看(过去 30 天)
Hi all,
I have the following function:
function [value_final] = myvalue(fd)
value_final = (fs + (fd.*(th.^2)));
end
Values for th and fs are constant, but for fd I use
fd = linspace(0,50,20);
th=5;
fs=8.5;
B = arrayfun(@myvalue,fd);
How can I create a matrix with in the first column each input value for 'fd' and in the second column the corresponding value for 'value_final' for each iteration? Later I want to include a range of values for 'fs' as well, so it would be nice to know which combination yields which value.
Thanks!

采纳的回答

Star Strider
Star Strider 2018-6-4
First, rewrite the function to include the additional parameters:
function [value_final] = myvalue(fd,fs,th)
value_final = (fs + (fd.*(th.^2)));
end
then pass them to it using an anonymous function within arrayfun:
fd = linspace(0,50,20);
th=5;
fs=8.5;
B = arrayfun(@(fd)myvalue(fd,fs,th),fd(:));
Out = [fd(:) B]
Since ‘myvalue’ is an external function, not an anonymous function, you have to pass the additional parameters to it. It will not pick them up from your workspace.
See if this does what you want.
  2 个评论
yoni verhaegen
yoni verhaegen 2018-6-4
Thanks! What should I change to this code if I want to include a range of values for 'fs' = linspace(0,50,20) as well?
Star Strider
Star Strider 2018-6-4
As always, my pleasure!
This will do what you want:
fd = linspace(0,50,20);
th=5;
fs = linspace(0,50,20);
B = arrayfun(@(fd)myvalue(fd,fs,th),fd(:), 'UniformOutput',false);
Bmtx = cell2mat(B);
Out = [fd(:) Bmtx];
Note that for this to work as you want it to, ‘fs’ must remain a row vector (as it is currently defined in this code). The ‘(:)’ in ‘fd(:)’ forces it to be a column vector. (The arrayfun call will still work if you force ‘fs’ to also be a column vector. The concatenation to create the ‘Out’ matrix will not, since the row sizes will not be the same.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by