How to call a function with a vector?
Show older comments
I need to modify the following code so that the function can be called with a vector for the value of b instead of just a single value. Any ideas?
4 Comments
dpb
on 6 Mar 2019
To vectorize expressions to operate on element basis, use the "dot" operators...
f=@(x) cos(x.^2);
Whereever else you have similar expressions, must make same fixes.
See the section "Array vs. Matrix Operations" under the "Operators and Elementary Operations" section.
Stephen23
on 6 Mar 2019
You need to understand the difference between array and matrix operations, otherwise your MATLAB code will produce nonsense and you won't know why:
>> result = (@(x) sin(x.^2), 0, 3, 50)
^^ Where is the function you want to call?
What you need:
>> result = fresnelS(@(x) sin(x.^2), 0, 3, 50)
^^^^^^^^ Your function !!!
PS: please do not post screenshots, posting actual text is much better (we already know what error message look like).
Answers (1)
Kevin Phung
on 6 Mar 2019
Edited: Kevin Phung
on 6 Mar 2019
if you are multiplying or dividing vectors, include the element-wise operator
.* %multiplication
./ %division
example documentation:
3 Comments
madhan ravi
on 7 Mar 2019
? where was vector multiplied or divided?
Kevin Phung
on 7 Mar 2019
Edited: Kevin Phung
on 7 Mar 2019
Thanks Adam. To clarify, given b is a vector , y and h would become vectors in:
h = (b-a)./n;
y = f(a)+f(b); %where f is cos(x^2)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!