How to make a local function that returns a vector

9 views (last 30 days)
I found a mistake in my question. I edited a part and the part is now underlined. Sorry for confusing way to ask.
Hello,
I wnat to make a local function that returns a vector or vectors.
For example, I will give the initial value of a vector, a(1,1), then the local function calculates a(1,2) based on the former value, a(1,1) until the last slot a(1,N), which will be calculated based on a(1,N-1).
I made a local function using function [y1, y2, ... , yN]=myfunction(x1, x2, ... , xM), but it did not work correctly. Is there any function or expression that can return a vector or vectors as the output?
I will attach my code.
% parameters
N=100;
div=0.1;
p=sqrt(3);
q=0.5;
r=2;
% vectors and initial values
a=zeros(1,N);
b=zeros(1,N);
a(1,1)=5;
b(1,1)=0.1;
% function
[a,b]=fcn2(N,p,q,r);
% arb. function
function [a,b]=fcn2(N,p,q,r)
for i=1:N
ka1=p+q*r;
kb1=p-q*r;
ka2=ka1+p*q;
kb2=kb1-q/r;
a(1,i+1)=a(1,i)+ka1*ka2;
b(1,i+1)=b(1,i)+kb1/(kb2+1);
end
end

Accepted Answer

Torsten
Torsten on 31 Dec 2023
Edited: Torsten on 31 Dec 2023
% parameters
N=100;
div=0.1;
p=sqrt(3);
q=0.5;
r=2;
% Initial values
astart=5;
bstart=0.1;
% function
[a,b]=fcn2(N,p,q,r,astart,bstart);
plot(1:numel(a),[a;b])
grid on
% arb. function
function [a,b]=fcn2(N,p,q,r,astart,bstart)
ka1=p+q*r;
kb1=p-q*r;
ka2=ka1+p*q;
kb2=kb1-q/r;
a = astart + (0:N)*ka1*ka2;
b = bstart + (0:N)*kb1/(kb2+1);
end
  4 Comments
Dyuman Joshi
Dyuman Joshi on 1 Jan 2024
Hello @Kosuke, if this answer solved your problem, please consider accepting the answer.

Sign in to comment.

More Answers (0)

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!