# Write a vectorial function from a scalar function

9 views (last 30 days)
Giuseppe Milazzo on 23 Jul 2022
Commented: Walter Roberson on 23 Jul 2022
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.

David Goodmanson on 23 Jul 2022
Edited: David Goodmanson on 23 Jul 2022
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 .
Walter Roberson on 23 Jul 2022
See vectorize()

### Categories

Find more on Numbers and Precision in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!