top of page

BASIC MATLAB CODING

 

close all;

clear all;

clc;             

 

%--------------------------------------- Assignment 1 ---------------------------------------%

%Input Value of N, M and X

N=input('N ,row = ');

M=input('M ,column = ');

X=input('X ,divider = ');

 

%random values in between -10 and 10

A = (rand(N,M)*20)-10;

Random_Value = A

 

%Write the matrix A to a file named “test.txt”

save('test.txt', 'A', '-ascii');

 

%Read “test.txt” and assign to the variable B

B = dlmread('test.txt');

 

%Find the maximum and minimum values of B

minB = min(min(B))

maxB = max(max(B))

 

%Round each element of B to the nearest integer

Nearest_Integer = round(B)

 

%Check if each element is divisible by X

for M = 1:M 

    for N = 1:N 

        if mod(Nearest_Integer(N,M),X) == 0

            Divisible(N,M) = 1;

        else

            Divisible(N,M) = 0;

        end

    end

end

Divisible_Number = Divisible  

 

%Write a new set of B to file named “test1.txt”

save('test1.txt', 'Divisible', '-ascii');

 

%----------------------------- Assignment 2 -----------------------------%

%Read the file name “test.txt” and assign the values to the variable B

B = dlmread('test.txt');

 

%Check Value of B

for M = 1:M 

    for N= 1:N 

        if B(N,M) < -5

            Compare(N,M) = 0;

        else if B(N,M) >= -5 && B(N,M) <= 5

                Compare(N,M) = 1;

            else if B(N,M) > 5

                   Compare(N,M) = 2;

                end

            end

        end

    end

end

Compare_Result = Compare

 

%Write a new set of B to file named “test1.txt”

save('test1.txt', 'Compare', '-ascii')

 

%change into row vector before plotting

New_B = reshape(Compare,1,[]);

Original_B = reshape(B,1,[]);

 

%Plot the values of new B w.r.t the original values of B

plot(Original_B,'b*-');     grid on;    hold;   plot(New_B,'r-o');

xlabel('Row Vector No.');       ylabel('Value');

legend('Original B','New B');

bottom of page