Borrar filtros
Borrar filtros

How to Make a function accept vector inputs

8 visualizaciones (últimos 30 días)
Chuzymatics Chuzymatics
Chuzymatics Chuzymatics el 21 de Dic. de 2013
Comentada: Walter Roberson el 29 de Mzo. de 2017
function Ml = myseries(t)
n=0;
while (n<10)
Ml = sum(t.^n/(gamma(n + 1)));
n = n+1;
end
The above code runs well as long as the input variable is a scalar; for vectorized inputs, it fails. What might be wrong?
  4 comentarios
Ben
Ben el 29 de Mzo. de 2017
sum(t.^n/(gamma(n + 1))) needs to have a . before the /
Walter Roberson
Walter Roberson el 29 de Mzo. de 2017
./ would only be needed if the right hand side, gamma(n+1) was a vector or matrix, but in this context it is a scalar.

Iniciar sesión para comentar.

Respuesta aceptada

Youssef  Khmou
Youssef Khmou el 21 de Dic. de 2013
You did not specify how the output should be , 1x1 or Nx1 , you can try this way :
function Ml = myseries(t)
n=0;
ctr=1;
while (n<10)
Ml(ctr) = sum(t.^n/(gamma(n + 1)));
n = n+1;
ctr=ctr+1;
end

Más respuestas (2)

Walter Roberson
Walter Roberson el 21 de Dic. de 2013
Your current code overwrites all of Ml each time through the "while" loop, and so is unlikely to be doing what you want.
for n = 0 : 9
Ml(n,:) = sum(t.^n/(gamma(n + 1)));
end
  4 comentarios
Walter Roberson
Walter Roberson el 21 de Dic. de 2013
Right, sorry,
for n = 0 : 9
Ml(n+1,:) = sum(t.^n/(gamma(n + 1)));
end
Chuzymatics Chuzymatics
Chuzymatics Chuzymatics el 22 de Dic. de 2013
I am proud to belong to this community; you all are legends. Many thanks

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 21 de Dic. de 2013
Editada: Image Analyst el 21 de Dic. de 2013
I think you can to what you want to do with one of these functions. Not sure what you want to do so pick one:
function theSum = myseries(t)
% Vectorized method.
n = 1:length(t);
theSum = sum(t.^n ./ (gamma(n + 1)));
function theSum = myseries(t)
% For loop method.
theSum = 0;
for n = 1 : length(t)
theSum = theSum + t(n)^n ./ gamma(n + 1);
end
This does something completely different than the other two answers but I think is what you were actually intending, which is trying to sum a series.
  5 comentarios
Image Analyst
Image Analyst el 23 de Dic. de 2013
Well he accepted your interpretation so I guess you were right. The Ml(2) was the sum of terms 1 and 2, the Ml(3) was the sum of terms 1, 2, and 3, and the element Ml(N) was term1 + term2 + term3 + term4 +....+termN. I thought he wanted just one sum - the sum of terms 1 through term N - not N sums, but I guess I was wrong.
Youssef  Khmou
Youssef Khmou el 23 de Dic. de 2013
ok

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by