1. Enter a 3 × 3 matrix. You can do this on a single line
code:
a=[1 2 3;4 5 6;7 8 9]
result:
2.How does Matlab output the values of the elements of a three dimensional array? Combine your two previous 3 × 3 matrices into a 3 × 3 × 2 array. Try c(:,:,1) = a; and similarly for b
code:
a=[1 2 3;4 5 6;7 8 9] %just a random matrix,same for b
b=[2 3 5;6 7 9;1 12 11]
c=zeros(3,3,2) %create a 3 × 3 × 2 array first,there we use zeros- matrix
c(:,:,1)=a %alter c1’s value
c(:,:,2)=b %alter c2’s value
result:
3. Plot a graph of sin(4πx) exp(−x)
Code:
x=0:0.01:2*pi
y=exp(-x).*sin(4*pi*x)
figure
plot(x,y)
title("the plot for function:sin(4πx)exp(−x)")
xlabel("the x line")
ylabel("the y line")
Result:
4.For the last exercise, generating an array using a for loop, it can be useful to allocate the memory space for the entire array at the beginning. You can do this by making an array of all zeros, easily done by using the zeros() command. Compare the speed difference between pre-allocating the memory space at the beginning versus allowing the array to “grow” as more space is needed. You can time things in Matlab using tic to start the timer, and toc to return the current value of the timer.
Code:
n=10
tic
a=zeros(1,n);
for i=1:n
a(i)=i
end
time1=toc
tic
b=[]
for j=0:n
b=[b,j]
end
time2=toc
fprintf("the alredy allocted method running time is:%.6f seconds\n",time1);
fprintf("the length grow method running time is:%.6f seconds\n",time2);
fprintf("different time is:%.6f seconds\n",time1-time2);
if(time1-time2>0)
fprintf("the second way is faster");
end
if(time1-time2<0)
fprintf("the first way is faster");
end
if(time1-time2==0)
fprintf("they run as the same speeed");
end
Result:
(actually,the result is dynamics)
5.Write a Matlab function that takes a vector or matrix of values as the input, converts this to a column vector using the colon operator (a = b(:);), and prints the numbers and whether they are odd or even to the screen; the output for my odd even([16 3 5 10 1]) might be: 16 even 3 odd 5 odd 10 even 1 odd You might find the size() function useful. i. Use a for loop to cycle through the input values. ii. Use a while loop to cycle through the input values.
Code:
a=[16,3,5,10,1]
b=a(:)
for i=1:5
if mod(b(i),2)==0
fprintf("%d even\n",b(i));
else
fprintf("%d odd\n",b(i));
end
end
Result:
6. As for the previous exercise, but intead of even or odd, report whether they are divisible by 2, 3, 4, or 5
Code:
a=[16,3,5,10,1]
b=a(:)
for i=1:5
if (mod(b(i),2)==0)
fprintf("%d can divide 2 with no remainder,vaild\n",b(i));
elseif (mod(b(i),3)==0)
fprintf("%d can divide 3 with no remainder,vaild\n",b(i));
elseif (mod(b(i),4)==0)
fprintf("%d can divide 4 with no remainder,vaild\n",b(i));
elseif (mod(b(i),5)==0)
fprintf("%d can divide 5 with no remainder,vaild\n",b(i));
else
fprintf("%d is not vaild\n",b(i));
end
end
Result: