matrix multiplication and summation

242 views Asked by At

i'm currently trying to remake my old function which takes a fixed value x:

function [res] = Eph(x,approximation,dot)
    a = [ 0.1818 0.5099 0.2802 0.02817];
    b = [ 3.2 0.9423 0.4029 0.2016];
if dot ~= 1 
res  =  sum(a.*exp(-b.*x));

Now I'm trying to pass a vector x (so the same procedure for each x_{i}) and I want to get back as a result also a vector res. Can someone give me a hint how to do it NOT using loops?

1

There are 1 answers

0
Luis Mendo On BEST ANSWER

I think what you want can be done with a combination of matrix multiplication (for the b.*x part) and bsxfun (for the a.*exp(...)) part:

res = sum(bsxfun(@times, a, exp(-x(:)*b)), 2);

Example with your code, scalar x:

>> x = 3;
>> res = sum(a.*exp(-b.*x))
>> res =
    0.1292

Example with my code, vector x:

>> x = [3 4 5];
>> res = sum(bsxfun(@times, a, exp(-x(:)*b)), 2)
res =
    0.1292
    0.0803
    0.0522