How to make a local function that returns a vector

9 vues (au cours des 30 derniers jours)
Kosuke
Kosuke le 31 Déc 2023
Commenté : Dyuman Joshi le 1 Jan 2024
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

Réponse acceptée

Torsten
Torsten le 31 Déc 2023
Modifié(e) : Torsten le 31 Déc 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 commentaires
Kosuke
Kosuke le 31 Déc 2023
Thank you for the additional information.
Dyuman Joshi
Dyuman Joshi le 1 Jan 2024
Hello @Kosuke, if this answer solved your problem, please consider accepting the answer.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by