When I run my function I want a row vector not a column

1 visualización (últimos 30 días)
furcifer
furcifer el 18 de Oct. de 2018
Editada: furcifer el 18 de Oct. de 2018
I have a simple function that generates large numbers. The ans is a column vector but I want a row. ans' changes it to what I want but I need it to run in the function. I'm not sure how to do that?

Respuesta aceptada

Stephen23
Stephen23 el 18 de Oct. de 2018
Editada: Stephen23 el 18 de Oct. de 2018
One simple solution is to use subscript indexing (but this will be quite inefficient):
function n = num(k)
n(1,1) = 1;
n(2,1) = 1;
k = 3;
while k<=100
n(k,1) = n(k-1)+n(k-2);
k = k+1;
end
The best solution is to preallocate the output array (much more efficient):
function n = num(k)
n = ones(100,1); % preallocate
k = 3;
while k<=numel(n)
n(k) = n(k-1)+n(k-2);
k = k+1;
end

Más respuestas (2)

furcifer
furcifer el 18 de Oct. de 2018
Editada: furcifer el 18 de Oct. de 2018
Here's what I have:
function [n] = num(k)
n(1)=1;
n(2)=1;
k = 3;
while k <=100
n(k) = n(k-1)+n(k-2);
k= (k+1);
end
The answer is a 1x100 double. (they probably look familiar) I need a 100x1 matrix.

furcifer
furcifer el 18 de Oct. de 2018
Editada: furcifer el 18 de Oct. de 2018
Yes, that's exactly it! Thank you for the help everyone.
eta: I'll use "zeros" and leave it defined as it is, but it's the allocation that really helped. Thanks, it was driving me mental.

Categorías

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

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by