learning basics of Matlab

Thread Starter


Joined Apr 15, 2011

I have just installed Matlab and need your help to learn the basics.

I have some experience with C++ and have written some basic programs such as adding two matrices etc. C++ provides an interaction between a user and a computer. In other words, suppose you write down a program for addition of two 2x2 matrices, and when it's run it asks the user to enter the elements of both matrices, once we are done with entering the elements, it will pop up the resultant matrix. The way my instructor, who himself is quite new to Matlab, was showing the running of Matlab it looked like Matlab doesn't provide the interaction. Do there exist things like "cin" and "cout" in Matlab? If I'm wrong, then could you please give me some simple program for addition of two 2x2 matrices so that I can play around and learn it? Thank you.

Last edited:

panic mode

Joined Oct 10, 2011
Rich (BB code):
%% have following three lines at top of each matlab program
clear all;
close all;

% ask for matrix size
rows=input('Number of matrix rows:');
cols=input('Number of matrix columns:');

% get elements of matrix A
for x=1:rows
    for y=1:cols

disp(' '); % just line break

% get elements of matrix B
for x=1:rows
    for y=1:cols

disp(' '); % line break

C=A+B; % add two matrices

disp(C); % display result


1. line can but does not have to end with semicolon, semicolon just hides output of that line
2. comments are % and %%
3. there is TONS of tutorials and code samples online
4. always write code in Editor, if you need to test it use breakpoints and stepping through
5. good idea is to clear everything at begin of each file (clear all variables, remove all graphs, etc.)
Last edited:

panic mode

Joined Oct 10, 2011
6. strings are enclosed in single quotes
7. converting number to string is through num2str
8. concatenating strings is done through strcat('abc', 'def','ghijkl');
9. transposed matrix is indicated by apostrophe such as C=A'+B'
10. unless specified, operations are matrix operations. for example multiplication etc. if needed to perform element to element operation, append dot after operator. for example

C=A*B is matrix multiplication
D=A*.B is element to element scalar multiplication


Joined Oct 2, 2009
Matlab can be used in the command mode or in the script mode.
In command mode, to create a 2 x 2 matrix, just enter something like:

a = [ 1 2 ; 3 4 ]

and this creates:

a =

1 2
3 4

if you want to display the matrix again, just type


You can do the same for b:

b = [ 5 6 ; 7 8 ]

And add the two by

a + b


c = a + b