0

I have the following function:

function [ res ] = F( n )
    t = 1.5;
    res = 0;
    if n <= 0
        return;
    end
    for i = 0:n-1
        res = res + power(-1,i)*power(t,2*i+1)/((2*i+1)*factorial(i));
    end 
end

I'm trying to pass an array to it so that I could see its output for every point in the array

F([2,3,4])

For some reason it refuses to act on the whole array, only giving me the output for the first member. Why is that?

EDIT: If I change

res = 0;

at the beginning to

res = 0 + n;
res = res - n;

It does work for the whole array.

1 Answer 1

1

The problem is res is not an array. You can do something like this:

function res = F(n)
  t = 1.5;
  m = length(n);
  res = zeros(m, 1);
  for  j = 1 : m
    for i = 0 : n(j) - 1
      res(j) = res(j) + power(-1, i) * power(t, 2 * i + 1) / ((2 * i + 1) * factorial(i));
    end; 
  end;
end;

The result for your example vector input:

>> F([2,3,4])

ans =

   0.375000000000000
   1.134375000000000
   0.727566964285714
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.