Storing outputs of for loop within an array

Hello, I am trying to create an array with the following code but i could not manage to that. I believe it must be a fundamental task but i am a beginner in Matlab. At the end of the loop i wanted to get all values of y1 and y2 depend on changing k values. Thank you for your help. (.m file is attached)
nf=1.5;
h=8*10^(-6);
ns=1.48;
lamda=1*10^(-6);
nc=1.45;
ko=(2*pi)/lamda;
kmax=sqrt((ko^2)*(nf^2)-(ko^2)*(ns^2));
c=round(kmax);
A=ones(c,2);
for k=1:100:c
beta=sqrt((ko^2)*(nf^2)-k.^2);
kf=sqrt(((nf^2)*(ko^2))-(beta.^2));
gammac=sqrt((beta.^2)-(ko^2)*(nc^2));
gammas=sqrt((beta.^2)-(ko^2)*(ns^2));
y1=kf*((((nf^2/ns^2)*gammas)+(nf^2/nc^2)*gammac)/(kf.^2-(nf^4*gammac.*gammas/(nc^2*ns^2))));
y2=tan(kf*h);
A(k)=[y1 y2];
end

Answers (1)

Change this to
y1=kf*((((nf^2/ns^2)*gammas)+(nf^2/nc^2)*gammac)/(kf.^2-(nf^4*gammac.*gammas/(nc^2*ns^2))));
y2=tan(kf*h);
This:
y1(k)=kf*((((nf^2/ns^2)*gammas)+(nf^2/nc^2)*gammac)/(kf.^2-(nf^4*gammac.*gammas/(nc^2*ns^2))));
y2(k)=tan(kf*h);

4 Comments

Put iterator as the index in order to avoid overwriting , in your case it’s (k)
Thank you for the immediate answer. You are totally right, i should have used k index. But now when i do that, it still does not calculate all the values of y1 and y2.
What do you expect you are dividing
kf*((((nf^2/ns^2)*gammas)+(nf^2/nc^2)*gammac)/(kf.^2-(nf^4*gammac.*gammas/(nc^2*ns^2))))
a numerator which is half of the denominator and you expect them to be integers?? And your loop is enormously large so when nearing the end the denominator grows rapidly towards infinity thats why you see all zeros towards the end. You should do something about the formula
Actually, my main goal is finding the intersection of two curves. I tried to solve the problem with fsolve function but i took too many errors. Then i decided to find separately the results of the functions in an array. You could see the results of them from the attached file. At least now i know the problem is not related to a loop error. Thank you for your help.

This question is closed.

Products

Release

R2018a

Asked:

mo
on 4 Nov 2018

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!