Write a vectorial function from a scalar function

I have a scalar function of multiple variables, let's say f = @(x,y) x^2 + y^2 (for example).
Now i have another vectorial variable z = [z1,z2,....,zn].' and i would like to build a vectorial function F such that F(i) = f(z(i),y).
Note that F needs to be a fun element and not sym, since i need to perform optimization using fminsearch.
Thank you in advance.

回答 (1 件)

David Goodmanson
David Goodmanson 2022 年 7 月 23 日
編集済み: David Goodmanson 2022 年 7 月 23 日

0 投票

Hi Giuseppi,
it looks like you intend, in this case,
f = @(z,y) z.^2 + y^2
Here .^ gives the element-by-element square of z, and in general you would use commands that preserve the vector nature of the input variable to give an output with the same dimension (row or column) as the input vector. In this case y^2 is a scalar so it is automatically added to each component of z.^2 .

4 件のコメント

Giuseppe Milazzo
Giuseppe Milazzo 2022 年 7 月 23 日
Hi David, thank you for the answer.
However my f function is a bit complicated, and has multiple occurrencies of x inside cos() and sin() functions.
Isn't there a way to take advantage of f to write the vector F?
Giuseppe Milazzo
Giuseppe Milazzo 2022 年 7 月 23 日
I have realized now that i could have done all in symbolic and use the function matlabFunction() to convert the expression.
David Goodmanson
David Goodmanson 2022 年 7 月 23 日
most Matlab functions including trig functions are vector-in vector-out functions so it is almost always possible to create a vector-in vector-out function using .* .^ ./ sin cos exp and so forth
Walter Roberson
Walter Roberson 2022 年 7 月 23 日
See vectorize()

サインインしてコメントする。

カテゴリ

製品

リリース

R2021a

質問済み:

2022 年 7 月 23 日

コメント済み:

2022 年 7 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by