How to make a local function that returns a vector

조회 수: 7 (최근 30일)
Kosuke
Kosuke 2023년 12월 31일
댓글: Dyuman Joshi 2024년 1월 1일
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

채택된 답변

Torsten
Torsten 2023년 12월 31일
편집: Torsten 2023년 12월 31일
% 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
Kosuke
Kosuke 2023년 12월 31일
Thank you for the additional information.
Dyuman Joshi
Dyuman Joshi 2024년 1월 1일
Hello @Kosuke, if this answer solved your problem, please consider accepting the answer.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by