开发者

Matlab - how to make this work for both scalars and vectors

Suppose function g takes a function f as a parameter, and inside g we have something like x = t*feval(f, u); however, f can be either scalar-valued or vector-valued. If it is vector valued, we want x开发者_如何学Go to be a vector as well, i.e. the feval statement to return the whole vector returned by f. How do we make this work for both scalar and vector cases?


As far as I can tell, what you are asking is already the default behavior in matlab. This means that if f returns a scalar, x will be a scalar and if it returns a vector x will be a vector.

In your example, this holds as long as t is also a scalar - otherwise the result will depend on how t*[output of f] is evaluated.

Example

function o1 = f(N)
o1 = zeros(1,N);
end

Here f returns a scalar if N=1 and a vector for N>1. Calling your code gives

x=feval('f', 1); % Returns x = 0

x=feval('f', 4); % Returns x = [0 0 0 0]


If the output of feval(f,u) can be either a scalar or a vector, and you want the result x to be the same (i.e. a scalar or a vector of the same length and dimension), then it will depend on what t is:

  • If t is a scalar, then what you have is fine. You can use either of the operators * or .* to perform the multiplication.
  • If t is a vector of the same length and dimension as the result from feval(f,u), then use the .* operator to perform element-wise multiplication.
  • If t is a vector of the same length but with different dimension that the result from feval(f,u) (i.e. one is a row vector and one is a column vector), then you have to make the dimensions match by transposing one or the other with the .' operator.
  • If t is a different length than the result of feval(f,u), then you can't do element-wise multiplication.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜