Return row vector adding on to the end

조회 수: 5 (최근 30일)
Dominic
Dominic 2022년 11월 9일
편집: Voss 2022년 11월 15일
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

채택된 답변

Voss
Voss 2022년 11월 10일
myFibon(4)
ans = 1×5
1 1 2 3 5
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
Dominic
Dominic 2022년 11월 13일
This helped a lot thanks so much! Is nargin necessary still new to matlab and I’m awful at it and any advice on how to improve
Voss
Voss 2022년 11월 15일
편집: Voss 2022년 11월 15일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by