Вы находитесь на странице: 1из 14

Introduction to MATLAB .

Study of Arrays, Conditional, Looping and Control Statements in


MATLAB:

MATLAB is a High-Performance language for technical computing. It integrates Computation,


Visualization, and Programming in an Easy-to-Use Environment where problems and solutions are
expressed in familiar Mathematical Notation. Typical uses include:
 Math and computation
 Algorithm development
 Modelling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including Graphical User Interface building
“MATLAB is an interactive system whose basic data element is an Array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those with
matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar
no interactive language such as C or FORTRAN.”

C MATLAB
C is considered as High Level Language MATLAB is High Level Language.
as well as Middle Level Language.
In C in 2D Array, blocks are indexed In MATLAB in 2D Array, blocks are
from Left to Right and then Up to indexed from Up to Down and then Left
Down. to Right.
In C, index starts from 0. In MATLAB, index starts from 1.
In C, Lines of Code are more as In MATLAB, Lines of code are Less as
compare to MATLAB for the same compare to C for the same program.
program.

MATLAB is an interactive program for numerical computation and data visualization. You can
enter a command by typing it at the MATLAB prompt '>>' on the Command Window.
COMMAND PURPOSE

clc Clears command window.

clear Removes variables from memory.

exist Checks for existence of file or variable.

global Declares variables to be global.

help Searches for a help topic.

lookfor Searches help entries for a keyword.

quit Stops MATLAB.

Who/whos Lists current variables/(long display).

MATLAB provides various useful commands for working with the system, like saving the current
work in the workspace as a file and loading the file later. It also provides various commands for
other system-related activities like, displaying date, listing files in the directory, displaying current
directory, etc.
The following table displays some commonly used system-related commands –

COMMAND PURPOSE

cd Changes current directory.

date Displays current date.

delete Deletes a file.

diary Switches on/off diary file recording.

dir Lists all files in current directory.

load Loads workspace variables from a file.


path Displays search path.

pwd Displays current directory.

save Saves workspace variables in a file.

type Displays contents of a file.

what Lists all MATLAB files in the current directory.

wklread Reads .wk1 spreadsheet fi

MATLAB provides the following input and output related commands −

COMMAND PURPOSE

disp Displays contents of an array or string.

fscanf Read formatted data from a file.

format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.

; Suppresses screen printing.

The fscanf and fprintf commands behave like C scanf and printf functions. They support the
following format codes −

FORMAT CODE PURPOSE

%s Format as a string.

%d Format as an integer.

%f Format as a floating point value.

%e Format as a floating point value in scientific notation.


%g Format in the most compact form: %f or %e.

\n or \t Insert a new or tab line in the output string.

“All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-
dimensional array and a matrix is a two-dimensional array.”
Array can be declared as:
a=[1, 2 ,3; 4,5,6]

Special Arrays in MATLAB :


 The zeros( ) function creates an array of all zeros
 The ones( ) function creates an array of all ones
 The eye( ) function creates an identity matrix.
 The rand( ) function creates an array of uniformly distributed random numbers on (0,1)

A magic square is a square that produces the same sum, when its elements are added row-wise,
column-wise or diagonally. The magic( ) function creates a magic square array. It takes a singular
argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.

Some important calculation of arrays/matrix….

 If A is a vector, then max(A) returns the maximum of A.


 If A is a matrix, then max(A) is a row vector containing the maximum value of each column.
 If A is a multidimensional array, then max(A) operates along the first array dimension whose size
does not equal 1, treating the elements as vectors. The size of this dimension becomes 1 while the
sizes of all other dimensions remain the same. If A is an empty array whose first dimension has zero
length, then max(A) returns an empty array with the same size as A.
 M = max(A, [], dim) returns the largest elements along dimension dim. For example, if A is a
matrix, then max(A, [], 2) is a column vector containing the maximum value of each row.
 M = max(A, [], nanflag) specifies whether to include or omit NaN values in the calculation.
For example, max(A, [], 'includenan') includes all NaN values in A while max(A, [],
'omitnan') ignores them.
 M = max(A, [], dim, nanflag) also specifies the dimension to operate along when using
the nanflag option.
 [M, I] = max(___) finds the indices of the maximum values of A and returns them in output
vector I, using any of the input arguments in the previous syntaxes. If the maximum value
occurs more than once, then max returns the index corresponding to the first occurrence.
 C = max(A, B) returns an array with the largest elements taken from A or B.
 C = max(A, B, nanflag) also specifies how to treat NaN values.
 If A is a vector, then min(A) returns the minimum of A.
 If A is a matrix, then min(A) is a row vector containing the minimum value of each column.
 If A is a multidimensional array, then min(A) operates along the first array dimension whose size
does not equal 1, treating the elements as vectors. The size of this dimension becomes 1 while the
sizes of all other dimensions remain the same. If A is an empty array with first dimension 0,
then min(A) returns an empty array with the same size as A.
 M = min(A, [], dim) returns the smallest elements along dimension dim. For example, if A is
a matrix, then min(A, [], 2) is a column vector containing the minimum value of each row.
 M = min(A, [], nanflag) specifies whether to include or omit NaN values in the calculation.
For example, min(A, [], 'includenan') includes all NaN values in A while min(A, [],
'omitnan')ignores them.
 M = min(A, [], dim, nanflag) also specifies the dimension to operate along when using
the nanflag option.
 [M, I] = min(___) finds the indices of the minimum values of A and returns them in output
vector I, using any of the input arguments in the previous syntaxes. If the minimum value
occurs more than once, then min returns the index corresponding to the first occurrence.
 C = min(A, B) returns an array with the smallest elements taken from A or B.
 C = min(A, B, nanflag) also specifies how to treat NaN values.

 For multiplication of respective each element of matrix a and b ‘a.*b’


 For division of respective each element of matrix a and b ‘a./b’

n=input('Enter Value of n: ')


x=magic(n);
x
for i=1:n
s=0;
for j=1:n
a(i,j)=x(i,j);
s=s+x(i,j);
end
a(i,n+1)=s;

end
for i=1:n+1
s=0;
for j=1:n
s=s+a(i,j);
end
a(n+1,i)=s;
end

Enter Value of n: > 3


n = 3
x =

8 1 6
3 5 7
4 9 2

a =

8 1 6 15
3 5 7 15
4 9 2 15
15 15 15 45

Conditional Statements:
Conditional statements enable you to select at run time which block of code to execute.

if (condition 1)
%do this
elseif (condition 2)
%do this
else
%do this
end
for loop to repeat specified number of times

for index = values


%statements
End

for index = values, statements, end executes a group of statements in a loop for a specified number
of times. values has one of the following forms:
 initVal:endVal — Increment the index variable from initVal to endVal by 1, and repeat execution
of statements until index is greater than endVal.
 initVal:step:endVal — Increment index by the value step on each iteration, or
decrements index when step is negative.
 valArray — Create a column vector, index, from subsequent columns of array valArray on each
iteration. For example, on the first iteration, index = valArray(:,1). The loop executes a maximum
of n times, where n is the number of columns of valArray, given by numel(valArray(1,:)). The
input valArray can be of any MATLAB® data type, including a character vector, cell array, or
struct.

Conditional statements, loops, branching


MATLAB Language Syntax

if, elseif, else Execute statements if condition is true

for for loop to repeat specified number of times

parfor Parallel for loop

switch, case, otherwise Execute one of several groups of statements

try, catch Execute statements and catch resulting errors

while while loop to repeat when condition is true

break Terminate execution of for or while loop

continue Pass control to next iteration of for or while loop


end Terminate block of code, or indicate last array index

pause Stop MATLAB execution temporarily

return Return control to invoking function

a=input('Enter a: ')
b=input('Enter b: ')
c=input('Enter c: ')
d=b*b-4*a*c;
if(d>0)
disp('Two Real Solution. ')
ans1=(-b+sqrt(d))/2*a
ans2=(-b-sqrt(d))/2*a

elseif(d==0)
disp('One Real Solution')
ans1=(-b)/2*a
else
disp('It Has No Solution')

end

Enter a: > 1
a = 1
Enter b: > 3
b = 3
Enter c: > 1
c = 1
Two Real Solution.
ans1 = -0.38197
ans2 = -2.6180
plot(X,Y)
plot(X,Y,LineSpec)
plot(X1,Y1,...,Xn,Yn)
plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
plot(Y)
plot(Y,LineSpec)
plot(___,Name,Value)
plot(ax,___)
h = plot(___)

 If X and Y are both vectors, then they must have equal length. The plot function plots Y versus X.
 If X and Y are both matrices, then they must have equal size. The plot function plots columns
of Y versus columns of X.
 If one of X or Y is a vector and the other is a matrix, then the matrix must have dimensions such
that one of its dimensions equals the vector length. If the number of matrix rows equals the vector
length, then the plot function plots each matrix column versus the vector. If the number of matrix
columns equals the vector length, then the function plots each matrix row versus the vector. If the
matrix is square, then the function plots each column versus the vector.
 If one of X or Y is a scalar and the other is either a scalar or a vector, then the plot function plots
discrete points. However, to see the points you must specify a marker symbol, for example,
plot(X,Y,'o').
 plot(X,Y,LineSpec) sets the line style, marker symbol, and color.
 plot(X1,Y1,...,Xn,Yn) plots multiple X, Y pairs using the same axes for all lines.
 plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn) sets the line style, marker type, and color for
each line. You can mix X, Y, LineSpec triplets with X, Y pairs. For
example, plot(X1,Y1,X2,Y2,LineSpec2,X3,Y3).

 If Y is a vector, then the x-axis scale ranges from 1 to length(Y).


 If Y is a matrix, then the plot function plots the columns of Y versus their row number. The x-axis
scale ranges from 1 to the number of rows in Y.
 If Y is complex, then the plot function plots the imaginary part of Y versus the real part of Y, such
that plot(Y) is equivalent to plot(real(Y),imag(Y)).
 plot(Y,LineSpec) sets the line style, marker symbol, and color.
 plot(___,Name,Value) specifies line properties using one or more Name,Value pair
arguments. For a list of properties, see Line Properties. Use this option with any of the input
argument combinations in the previous syntaxes. Name-value pair settings apply to all the
lines plotted.
 plot(ax,___) creates the line in the axes specified by ax instead of in the current axes (gca).
The option ax can precede any of the input argument combinations in the previous syntaxes.
 h = plot(___) returns a column vector of chart line objects. Use h to modify properties of a
specific chart line after it is created.
 Following attributes can be added to the plot:
 plot(x,y,'k:h','LineWidth',2.5,'MarkerSize',3,'MarkerEdgeColor','g')
‘k:h’ specifies color and the values later after the other attributes specifies respective values.

Line Style Description Marker Description

- Solid line (default) O Circle


-- Dashed line + Plus sign
: Dotted line * Asterisk
-. Dash-dot line . Point
X Cross
S Square
D Diamond

Color Description Color Description

Y yellow G green
M magenta B blue
C cyan W white
R red K black
Y = sin(x); X = wt; 0<=t<=0.4; W=2πf; F=50;

f=50;
w=(2*pi*f);
t=0:0.001:0.04;
x=w*t;
y=sin(x);
plot(x,y,'k:h','LineWidth',2.5,'MarkerSize',3,'MarkerEdgeColor','g');
hold on;
plot(y,x,'r:h','LineWidth',5,'MarkerSize',4,'MarkerEdgeColor','k');
hold off;
title 'sine';
xlabel 'x:wt:t:0-0.004';
ylabel 't:0-0.04';
grid;

>>for 3D graph
Plot3(x,y,z)
>>for bargraph
bar(x,y)
>>for horizontal bargraph
barh(x,y)
>>for piechart
Pie(x,y)
>>to display multiple plots in a single figure
subplot(2,2,1)
“Monte Carlo “simulation is a technique used to study how a model responds to randomly generated
inputs. It typically involves a three-step process:

1. Randomly generate “N” inputs (sometimes called scenarios).


2. Run a simulation for each of the “N” inputs. Simulations are run on a computerized model of the
system being analysed.
3. Aggregate and assess the outputs from the simulations. Common measures include the mean
value of an output, the distribution of output values, and the minimum or maximum output
value.
“Systems analysed using Monte Carlo simulation include financial, physical, and mathematical
models. Because simulations are independent from each other, Monte Carlo simulation lends itself
well to parallel computing techniques, which can significantly reduce the time it takes to perform
the computation.”

The MATLAB language provides a variety of high-level mathematical functions you can use to
build a model for Monte Carlo simulation and to run those simulations. MATLAB is used for
financial modelling, weather forecasting, operations analysis, and many other applications.

s=0;
c=0;
for i=1:10000
x=rand-0.5;
y=rand-0.5;
if(x<=0.5 && x>=-0.5)
if(y<=0.5 && y>=-0.5)
s=s+1;
plot(x,y,'r+');
end
end

if( 0.25>=x*x + y*y)


c=c+1;
plot(x,y,'b+');
end
hold on;
end
hold off;

pi=4*c/s;
disp(pi);

Pi = 3.1420

n=13;
for i=1:n

a=sort(rand(n,1))*2*pi;
r=randi(9,1,1);
x=cos(a).*r
y=sin(a).*r;

plot([x; x(1)],[y; y(1)]);

end
d=sort(y);
e=sort(x);
rady=(d(n)-d(1))/2;
radx=(e(n)-e(1))/2;
centx=(e(n)+e(1))/2;
centy=(d(n)+d(1))/2;
inside=0;
n1=1200;
while(n1>0)
p=e(n)*rand;
q=d(n)*rand;
if(radx>=rady)
if((q-centy)<sqrt((radx*radx)-((p-centx)*(p-centx))))
inside=inside+1;
areac=pi*(radx*radx);
% plot(p,q,'r.');
end
end
if(rady>radx)
if((q-centy)<sqrt((rady*rady)-((p-centx)*(p-centx))))
inside=inside+1;
areac=pi*(rady*rady);
% plot(p,q,'r.');
end
end
% hold on;
n1=n1-1;
end
%hold off;
ans=areac*(inside)/1200;

fprintf('%f',ans);

Вам также может понравиться