Clear Filters
Clear Filters

Having an array as an input for a user generated function

2 views (last 30 days)
I created a function called seq(n). It takes in n, an integer, and gives the nth element of the sequence, x_0=1 x_(n+1)= x_n + 1/x_n for n=1,2,3,etc.
I want to list out a part of the sequence by setting x = [1 2 3 4 5 6 ... m], and computing seq(x), but if I do that, the only thing I get is seq(1).
How can I fix this so that like other functions, such as sin(x), if I put an array into the function input, I get an array of corresponding function values.
Thank you,
  3 Comments
CHANYANG
CHANYANG on 10 May 2014
function [x_n]=seq(n)
i=1;
ctr=1;
for k=1:n
x_n(ctr)=i+1/i;
k=k+1;
i=x_n;
ctr=ctr+1;
end
x_n=i;
end
Image Analyst
Image Analyst on 10 May 2014
Edited: Image Analyst on 10 May 2014
So does that do what you want? One thing I noticed immediately is that the function is supposed to take in a vector like x = [1 2 3 4 5 6 ... m] and not a single number like n or m. At least, that's what you originally said. That's why, in my code below, I took m from that last element of x since x seemed to be an integer sequence. Lots of other problems with the code, such as redefining k inside the loop, which doesn't effect it since it totally ignores that once the loop starts again, but it's very bad programming practice. Also, there's no need for the ctr variable since you can just use k. No need for i either for that matter!

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 8 May 2014
Well the most simple basic way is a for loop
function out = seq(x)
m = x(end); % m is the last element of the x that was passed in.
out(1) = 1; % this is x_0
for n = 2 : m
out(2) =
and so on. This will give you all the terms. Not hard at all. Give it a try. Try to complete it.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!