Try lots of differences way simplifying my code but doesn't work well. How can I fix it?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Need help for simplifying my matlab code. I have tried function handle, cellfun, anonymous function, arrayfun. I do not know am I using those function fully correct, but the outcome doesn't really satisfy my requirment.
lambda = 1;
k = 2*pi/lambda;
w = 2*pi*v/lambda;
z=linspace(0,10,10000);
t=linspace(0,10,10); %time
theta=(pi)*rand(1,length(t)); %random phase
for a=1:length(t)
u1=1./(1+exp(-2.*(10e4).*(t(a)-z./v))); %step function
u2=1./(1+exp(-2.*(10e4).*(t(a)-z./v-1)));
u3=1./(1+exp(-2.*(10e4).*(t(a)-z./v-2)));
u4=1./(1+exp(-2.*(10e4).*(t(a)-z./v-3)));
u5=1./(1+exp(-2.*(10e4).*(t(a)-z./v-4)));
u6=1./(1+exp(-2.*(10e4).*(t(a)-z./v-5)));
u7=1./(1+exp(-2.*(10e4).*(t(a)-z./v-6)));
u8=1./(1+exp(-2.*(10e4).*(t(a)-z./v-7)));
u9=1./(1+exp(-2.*(10e4).*(t(a)-z./v-8)));
u10=1./(1+exp(-2.*(10e4).*(t(a)-z./v-9)));
del_u1=u1-u2;
del_u2=u2-u3;
del_u3=u3-u4;
del_u4=u4-u5;
del_u5=u5-u6;
del_u6=u6-u7;
del_u7=u7-u8;
del_u8=u8-u9;
del_u9=u9-u10;
y1=del_u1.*cos(k.*z-w.*t(a)+theta(1));
y2=del_u2.*cos(k.*z-w.*t(a)+theta(2));
y3=del_u3.*cos(k.*z-w.*t(a)+theta(3));
y4=del_u4.*cos(k.*z-w.*t(a)+theta(4));
y5=del_u5.*cos(k.*z-w.*t(a)+theta(5));
y6=del_u6.*cos(k.*z-w.*t(a)+theta(6));
y7=del_u7.*cos(k.*z-w.*t(a)+theta(7));
y8=del_u8.*cos(k.*z-w.*t(a)+theta(8));
y9=del_u9.*cos(k.*z-w.*t(a)+theta(9));
y10=u10.*cos(k.*z-w.*t(a)+theta(10));
yy=y1+y2+y3+y4+y5+y6+y7+y8+y9+y10;
figure(1)
plot(z,yy); grid on; axis image;
drawnow;
end
The equation is not complicated but I got hard time trying to simplify it. I'm suppose to repeat the equation 1000 times, means length(theta)=1000, u1~u1000, del_u1~del_u999, y1~y1000, yy=y1+y2+...y1000.
How can I simplify my code?
3 commentaires
Stephen23
le 27 Oct 2020
"How can I simplify my code?"
Do NOT use numbered variables.
Using numbered variables like that is a sign that you are doing something wrong.
MATLAB is designed for operating on entire vectors/matrices, and that is what you should do too. Splitting up your data into numbered variables forces you into either repeating code many times or using slow and inefficient methods to access your data. Do not make accessing your data so difficult!
Keep data together in vectors/matrices. When possible apply operations to the entire vectors/matrices:
When required use loops and indexing. That is how you will simplify and improve your code.
Réponses (0)
Voir également
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!