Vectorize function evaluation in MATLAB

跟風遠走 提交于 2021-01-29 12:50:26

问题


I have the following function,

function Vectorize()
a = randn(1,5)
b = randn(1,5)
c = zeros(1,5)
for i=1:5
c(i) = (a(i) - b(i))/(1+a(i)/2+b(i)/3)
end

I want to vectorize the above function evaluation and replace the for loop.

I could do c = a -b, that finds the difference between two row vectors.I am not sure how to handle the division a/2 and b/2.

Could someone help?


回答1:


You need the element wise division operation ./

c = (a - b)./(1+a/2+b/3)

If you divide a vector by a scalar, this is not required, but where you divide an array by an array you will have to use ./ in your case. See here for the other element wise operators.



来源:https://stackoverflow.com/questions/53362840/vectorize-function-evaluation-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!