1. Write a program to print a matrix of order 5x3 using for loop?
Solution.
rows = 5;
cols = 3;
matrix = zeros(rows, cols);
count = 1;
for i = 1:rows
for j = 1:cols
matrix(i, j) = count;
count = count + 1;
end
end
disp('5x3 Matrix:');
disp(matrix);
2. Write a program which gets value from user and tell that
number is even or odd.
Solution:
n = input('Enter a number: ');
if mod(n,2) == 0
disp('Even number');
else
disp('Odd number');
end
3. Write a program in matlab to display the first 10 natural numbers.
for i = 1:10
disp(i)
end
4. Write a program in matlab that calculates and prints the sum of cubes
of even numbers up to a specified limit (e.g., 20) using a while loop.
limit = 20;
i = 2;
sumCubes = 0;
while i <= limit
sumCubes = sumCubes + i^3;
i = i + 2;
end
fprintf('The sum of cubes of even numbers
up to %d is %d.\n', limit, sumCubes);
5. Calculate the sum S of elements ai =√2i-1, i=1, 2, ..., until the sum
will exceed 20.
S=0;
i=1;
while S<20
S=S+sqrt(2*i-1);
i=i+1
end
6. Write a MATLAB program to input the coefficients of a quadratic equation and
display whether the roots are imaginary, repeated, or real based on the
discriminant.
a = input('Enter coefficient a: ');
b = input('Enter coefficient b: ');
c = input('Enter coefficient c: ');
D = b^2 - 4*a*c;
if D < 0
disp('Roots are imaginary');
elseif D == 0
disp('Roots are repeated');
else
disp('Roots are real');
end