简体   繁体   中英

Perform a function on each value of a vector in matlab?

I have a vector, a, shape (10000,1) filled with values. I also have vector b, same shape, filled with zeros. I want to take my function, apply it to each value in vector a, return those values into vector b. Below is what I tried, as well as a few variations of this. How can I perform this function on each value of the vector and replace each zero in vector b with what that function returns?

for i=1:length(a)
    b(i) = function(a)
end

You can use arrayfun to do this

b = arrayfun(@someFunction, a); % Calls b(i) = someFunction(a(i)) for all elements of a

(Although it's common in MATLAB to try and make someFunction be " vectorised ", so that you can instead say simple b = someFunction(a) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM