Return row vector adding on to the end
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Trying to make the sequence show the values till the specified spot but idk how to return as a vector
IE if we say myFibon(4) the anwser is 5 but i want to show all the values from that sequence till 5
here is my code and description so far.
% Function Declaration:
function [result] = myFibon(x)
%% The Fibonacci numbers are generated by the sequence
% What does the sequence look like? 1,1,2,3,5,8,13
% Can you work out what the next term is?
%
%
% 1 + 1 = 2
% 1 + 2 = 3
% 2 + 3 = 5
% 3 + 5 = 8
% 5 + 8 = 13
%
% Write a recursive function to compute the Fibonacci numbers
% F0 up and through to Fx, where "x" was specified as
% an input parameter.
%
%% Use the Fibonacci relationship
% Given that F0=F1=1
% Fn = Fn−1 + Fn−2
% Return the "result" as a row vector of the Fibonacci sequence.
% Submit your function
result = [1,1];
if x > 1
result = myFibon(x - 1) + myFibon(x - 2);
result(end + 1) = result;
else
result = 1;
end
0 Kommentare
Akzeptierte Antwort
Voss
am 10 Nov. 2022
myFibon(4)
function seq = myFibon(x,seq)
if nargin < 2
seq = [];
end
if x > 1
temp1 = myFibon(x-1,seq);
temp2 = myFibon(x-2,seq);
seq = [temp1 temp1(end)+temp2(end)];
elseif x == 1
seq = [1 1];
else
seq = 1;
end
end
2 Kommentare
Voss
am 15 Nov. 2022
Bearbeitet: Voss
am 15 Nov. 2022
nargin is not strictly necessary, but it's convenient. It's there so that you can call myFibon with one argument only. That is, you don't have to specify the empty sequence when you call it; it does that for you.
function seq = myFibon(x,seq) % x: number, seq: sequence
if nargin < 2 % if no sequence is given
seq = []; % use the empty sequence
end
[ Notice that any time myFibon is called recursively (i.e., called from within myFibon), it is called with two inputs (i.e., including the sequence). This is key to building the Fibonacci sequence recursively, in this implementation. ]
Allowing one-input call is just so that you can say
myFibon(4)
and not have to say
myFibon(4,[])
That's it.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!