编写脚本时是否可以同时计算所有值? [英] Is it possible to compute all the values at the same time when writing a script?
问题描述
定义功能时,说TEST = @(t) t.^2
.如果输入是向量,请说[1,2,3,4]
,TEST([1,2,3,4]) = [1,4,9,16]
.
When defining a function, say TEST = @(t) t.^2
. If the input is a vector, say [1,2,3,4]
, TEST([1,2,3,4]) = [1,4,9,16]
.
如果定义的函数采用脚本形式,我们可以做类似的事情吗?我的意思是,如果我有脚本,请说TEST.m,这样ret = TEST(x,y,z)
会在知道x
,y
和z
的数值时输出一个值.假设当x
,y
固定时,假设分别为0、1,我想计算100个不同的z
值,范围从1到100.是否可以输出TEST(0,1,1:1:100)
而无需编写for循环或更改脚本TEST.m的任何内容?
Can we do similar thing if the function defined is in script form? What I mean is that if I have a script, say TEST.m such that ret = TEST(x,y,z)
which outputs a value when knowing numerical values of x
, y
and z
. Suppose I want to calculate 100 different values of z
ranging from 1 to 100 when x
, y
are fixed, say at 0, 1 respectively. Is it possible to output TEST(0,1,1:1:100)
without writing a for loop or changing any contents of the script TEST.m?
问这样的问题的原因来自于计算时间.通常,我拥有的脚本可能有点复杂,因此单个值的计算可能要花几分钟的时间.编写for循环以输出它会非常耗时.我想编写parfor
循环,但是对于我来说,计算时间仍然很长,无法继续使用.我想知道是否可以一次计算所有100个值.我是程序员的入门者,我希望在这篇文章之后能得到满意的答复.感谢您的所有帮助.
The reason to ask such question comes from the computation time. Usually, the script I have may be a little complicated so that the calculate of a single value may take few minutes to go. Writing for-loop to output it can be very time-consuming. I think of writing parfor
loop, but the computation time is still long to me for further uses. I wonder if I can calculate all the 100 values at a time. I am a starter of programmer, and I hope I can get satisfactory answers after this post. Thanks for all your help.
推荐答案
您可以定义一个新的匿名函数,以获取固定值作为参数,并获取矢量作为输入.然后使用arrayfun
对数组的所有值进行计算.
You cab define a new anonymous function to get the fixed values as parameters, and the vector as input. Then use arrayfun
to compute it on all values of the array.
假设您具有以下功能:
function ret = TEST(x,y,z)
ret = f(x)+g(y)+h(z);
end
function r = f(x)
r = x^2;
end
function r = g(y)
r = y^3;
end
function r = h(z)
r = z^4;
end
您从以下位置调用它:
x = 2;
y = 3;
z = 1:5;
T = @(z) TEST(x,y,z);
arrayfun(T,z)
所以T
是一个新函数,将x
和y
视为常量,并且仅以z
作为输入.然后arrayfun
取T
并为z
中的每个元素进行计算,您将得到:
So T
is a new function that treat x
and y
as constants, and only have z
as input. Then arrayfun
takes T
and compute it for every element in z
, and you get:
ans =
32 47 112 287 656
现在,如果x
和y
可以保持不变,则可以将arrayfun
与更多的矢量一起使用,例如[a,b,c] = arrayfun(T,z,w,v)
.
Now, you can use arrayfun
with more vectors, like [a,b,c] = arrayfun(T,z,w,v)
, if x
and y
can stay constant.
希望它能回答您的问题;)
Hopes it answers your question ;)
这篇关于编写脚本时是否可以同时计算所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!