3. Interactive use
>> x=2*pi
x =
>> M'
ans =
6.2832
>> M= [pi exp(pi); 0 -1]
M =
3.1416 23.1407
0 -1.0000
3.1416 0
23.1407 -1.0000
>> M(:)
ans =
3.1416
0
23.1407
-1.0000
4. Arithmetic operations
>> v=[3;4]
v =
3
4
>> p=v.*v
>> size(v)
ans =
2 1
>> q=v*v'
p =
9
16
>> sum(p)
ans =
25
q =
9 12
12 16
>> r=v'*v
r =
25
5. Testing and Looping : if else and switch statements
clear all
a=4;
b=6;
if(a==4)
disp('equality');
end
clear all
a=input('enter number=');
b=input('enter number=');
c=input('choose option
add=1,sub=2,mul=3,div=4 :');
switch c
case 1
p=a+b
disp(['sum=' num2str(p)]);
clear all
disp(['sum=' num2str(p)]);
case 2
q=a-b
disp(['sub=' num2str(q)]);
case 3
r=a*b
disp(['mul=' num2str(r)]);
case 4
s=a/b
disp(['div=' num2str(s)]);
otherwise
disp('not valid');
end
clear all
a=4;
if(a>0)
disp('case one');
else
disp('case two')
end
6. For and While statements
clear all
for x=0:0.1:10
fprintf(1,'x is %dn',x)
end
x=1;
while(x<10)
x=x*1.1;
end
for k=1:20
fprintf(1,'k=%d, ans=%.2f n',k,k*pi);
end
12. Effective matlab coding : using reserved memory space using zeros command
clear all
N=16384;
tstart=cputime;
for k=1:N
x(k)=k;
y(k)=N-k+1;
end
clear all
N=16384;
tstart=cputime;
x=zeros(N,1);
y=zeros(N,1);
z=zeros(N,1);
for k=1:N
x(k)=k;end
for k=1:N
z(k)=x(k)+y(k);
end
tstop=cputime;
fprintf(1,'Time using loops = % .3f n', ...
tstop-tstart);
x(k)=k;
y(k)=N-k+1;
end
for k=1:N
z(k)=x(k)+y(k);
end
tstop=cputime;
fprintf(1,'Using preallocation = % .3f n', ...
tstop-tstart);
13. Vectorization is most effective way writing matlab code
clear all
N=16384;
tstart=cputime;
k=1:N;
x=k;
y=N-k+1;
z=x+y;
tstop=cputime;tstop=cputime;
fprintf(1,'Using vectorization = % .3f n', ...
tstop-tstart);