Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

learning basics of Matlab

Status
Not open for further replies.

PG1995

Active Member
Hi

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.

Note: I don't know which forum this query really belongs to. If it's not relevant in this section, then please move it the right forum. Thanks.

Regards
PG
 
Last edited:
For input, you can use the 'input' function. For output, you can use the 'fprintf' function.

>> help input
input Prompt for user input.
R = input('How many apples') gives the user the prompt in the
text string and then waits for input from the keyboard.
The input can be any MATLAB expression, which is evaluated,
using the variables in the current workspace, and the result
returned in R. If the user presses the return key without
entering anything, input returns an empty matrix.

R = input('What is your name','s') gives the prompt in the text
string and waits for character string input. The typed input
is not evaluated; the characters are simply returned as a
MATLAB string.

The text string for the prompt may contain one or more '\n'.
The '\n' means skip to the beginning of the next line. This
allows the prompt string to span several lines. To output
just a '\' use '\\'.
 
Wish I could afford to buy MATLAB.
 
Last edited:
Last edited:
Thank you, Dougy.

It looks like you are quite proficient with Matlab so be ready to help me! :) Right now, I'm reading a basic help file for Matlab. Let's see where I get stuck.

@Mikebits: Yes, it's true that the student version is comparatively inexpensive. I was able to get its copy from a college. The alternative suggested by dougy83 is a good one.

Best wishes
PG
 
Last edited:
This is a great book:
MATLAB for Engineers 3rd ed. - Holly Moore
Don't worry about the word "engineer" in the title, the book is targeted for finished high school.

Matlab programs are scripts, and you can't run them separately without matlab.

First you have to understand matlab prompt (which is easy).
Whatever command you type in prompt, only variables are constructed in memory,
and the command it self is, in a way discarded, accept it can be found in history.
You can now type new commands and use existing vars from memory.

To see what is in memory the command is "whos".
To clear the var a from memory the command is "clear a".
To clear all memory the command is just "clear".

Hope this helps.
 
Last edited:
Thank you, Vlad.

I understand what you mean by "matlab prompt". It's something like DOS prompt for, say, C++ which is just used to feed the values to variables already declared in the compiled program. Today, I have read some documentation on Matlab and have also read almost 100 pages from Matlab Demystified by McMahon. Could you please link me to some simple source to learn Matlab prompt? I just want to learn basics. By the way, after reading the documentation at least now I can use Matlab as a calculator. Thanks.

Regards
PG
 
Last edited:
Technically it is called command window.

To declare and initialize a row vector, you type:
a=[1 2];
To declare and initialize a column vector, you type:
b=[3;4];
To declare and initialize a 2x2 matrix, you type:
c=[5 6;7 8];
To declare and initialize another 2x2 matrix, you type:
d=[9 10;11 12];
To add matrices c and d you type:
e=c+d;
Row times column is dot product (inner product):
f=a*b;
Column times row is a matrix (outer product):
g=b*a;
Entry wise product is:
h=c.*d;
Matrix product is:
j=c*d;

To better understand this observe your "workspace window" and size info.
If you don't write semicolon ( ; ) at the end of expression you get output printout on screen.
(actually don't write ; for above examples just to see what's going on.)
 
Last edited:
Once again, my thanks for the help, Vlad.

If you have used C or C++ then you can understand what I'm saying. For instance, you can see here how I can add any two 2x3 matrices. I have also included the code below which I wrote more than a year ago. Is this possible to write such a program in Matlab which runs in similar fashion? I hope now you can see what I'm after. Thank you.

Code:
/ sum_of_two_2x3_matrices.cpp
// read two 2x3 matrices and find sum

#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

int main()
{
        const int R = 2, C = 3;
        int r, c;
        float m1[R][C];
        float m2[R][C];
        float sum_m3[R][C];
        float sum = 0;

        cout << "Enter matrix #1 below\n\n";

        for ( r=0; r<R; r++)
        {
                for (c=0; c<C; c++)
                {
                        cout << "enter entry for row #" << (r+1) << " and column"
                             << " #" << (c+1) << ": ";
                        cin >> m1[r][c];
                }
        }

        cout << "\n\nEnter matrix #2 below\n\n";

        for ( r=0; r<R; r++)
        {
                for (c=0; c<C; c++)
                {
                        cout << "enter entry for row #" << (r+1) << " and column"
                             << " #" << (c+1) << ": ";
                        cin >> m2[r][c];
                }
        }

        for ( r=0; r<R; r++ )
        {
                for ( c=0; c<C; c++)
                {
                        sum_m3[r][c] = m1[r][c] + m2[r][c];
                }
        }

        cout << "\n Sum of matrix #1 and matrix #2 is given below\n\n";

        cout << setw(10) << "" << setw(10) << "col 1" << setw(10) << "col 2" << setw(10)
             << "col 3\n";

        for ( r=0; r<R; r++ )
        {
                cout << "\n" << setw(9) << "row " << r+1;

                for ( c=0; c<C; c++ )
                {
                        cout << setw(10) << sum_m3[r][c];
                }
        }

        cout << "\n\n";

        system("pause");
        return 0;

}


Regards
PG
 
Last edited:
Yes, that is perfectly possible.
input,disp and fprintf are like cin and cout in c++. fprintf is very similar to printf in c.
I don't have an example, but the book I recommended is full of simple examples,
simple exercises and problems.
 
Last edited:
You could rewrite that code in matlab if you wanted, using for loops, input to read, fprintf to write, etc.

You can also use the matlab format for entering matrices (i.e. data enclosed in square brackets, columns separated by space or comma, and rows separated by semicolon). e.g. the following code allows the user to enter 2 matrices and prints the sum of them as the result.

Code:
A = input('Please enter matrix A: ')
B = input('Please enter matrix B: ')

fprintf('A + B = \n\n');
sum = A + B;
disp(sum);

This will give the following output (obviously values have been entered for the matrices)
Code:
Please enter matrix A: [1 2 3; 1 1 1]

A =

     1     2     3
     1     1     1

Please enter matrix B: [2 2 2; 4 5 6]

B =

     2     2     2
     4     5     6

A + B = 

     3     4     5
     5     6     7

To run the top snippet, you can either save it as a file and run the file (from the matlab editor, or by entering the filename at the matlab command prompt), or you can just cut and paste the snippet into the commandline (copy/paste all lines of the program at once).
 
Thank you very much, Vlad, Dougy.

@Vlad: I had looked for the book you had recommended but it wasn't available. I have an ebook "Matlab Demystified", as I mentioned my previous post. I have read three chapters of that book and all what those chapters present is how to use Matlab as a computation and graphic calculator! On the other hand reading those chapters have helped me to grasp understanding of basic commands.

@Dougy: Thanks a lot for the code. That was very helpful. Yes, now it seems Matlab can used the way I was thinking. Right now II'm playing around with it. Will update you with the progress.

Thank you.

Best wishes
PG
 
Hi

The code below doesn't run. I can't seem to correct it. Only the first line, "Please enter matrix A:" is executed. I have also included error lines at the bottom. Please help me with it.

In C++ there exists only "cin" and "cout". Could you please briefly tell where each of the "fprintf()", "disp()", and "input()" is used? Thank you.

Code:
fprintf('Please enter matrix A: ');
A = input();
fprintf('Please enter matrix A: ');
B = input();

fprintf('\n\n\''Hello\n\n');
 
fprintf('A + B = \n\n');
sum = A + B;
disp(sum);

Error(s):
Code:
Please enter matrix A: Error using input
Not enough input arguments.

Error in matrix_addition2 (line 2)
A = input();
 
You have to pass a string to input function as a parameter.
In your case pass an empty string like this:
A = input('');

fprintf is more powerful than disp and lets you combine strings with variable values in screen output,
in any way you want.
printf also exists in C and fprintf is very similar.
 
Last edited:
The input function needs a prompt string, e.g. input('please enter matrix A: '), if you don't want to specify a prompt, just use input('') i.e. give it an empty string as the prompt. If you have a look at my example, you'll see how the prompt is specified.

The input command allows the user to enter an expression that is evaluated (and/or converted) by matlab before assigning to the output variable ('A' in your case). The user could enter [1 1 1; 2 2 2] when the program asks for matrix A, and A + 1 when the program asks for matrix B; the result is that A + 1 is evaluated before assigning to matrix B. Sorry if this is confusing. If you enter something matlab can't understand, e.g. C, matlab will tell you that C doesn't exist.

The fprintf function is basically the same as the C printf statement. I think some of the format characters are different though. It just prints formatted text to the console/command window.

The disp function displays the matrix passed to it after formatting it. e.g. you can use it to display all of the elements of A using disp(A). You can also display strings, e.g. disp(['First element of A is ' num2str(A(1,1))]
 
Last edited:
Thank you, Vlad, Dougy. It would have been quite difficult learning Matlab without your help.

vlad777 said:
fprintf is more powerful than disp and lets you combine strings with variable values in screen output,
in any way you want.

Could you please tell me how to combine string and variable values using fprintf? You can use the code given below. Thanks.

dougy83 said:
The disp function displays the matrix passed to it after formatting it. e.g. you can use it to display all of the elements of A using disp(A). You can also display strings, e.g. disp(['First element of A is ' A(1,1)]

It's not working for me. Where am I going wrong? Please let me know. Thanks.


Code:
% the code below is used to add any two matrices

fprintf('Please enter matrix A: \n');
A = input('')
fprintf('Please enter matrix B: \n');
B = input('')

fprintf('\n\nHello\n\n');
 
fprintf('A + B = \n\n');
sum = A + B;
fprintf(['A + B = \n\n'sum);                                % error
disp(['A + B = \n\n'A(1,1)]);                               % error
 
Last edited:
Hi

Could you please tell me what I did wrong? When I press "s" I get an error which is given below.

Code:
% the following program is used to draw graphs of three basic trignometric 
% functions

clear
clc

A=1;
ph=0;

fprintf('if a problem occurs while execution please enter CTRL+C for termination\n\n\n');

choice = input('which trig. function you want to draw, enter "s" for sin , eneter "c" for cos, and for tan enter "t": ' );
                
if (choice==s)
    fprintf('the sine function will be drawn using this equation, A.*sin(x+ph)\n');
    drawFunction = A.*sin(x+ph);
    fprintf('please enter the range for the graph\n');
    min = input('enter lower range value: ');
    max = input('enter maximum value for your range: ');
    range = [min:0.01:max];
    default1=input('do you want to change default values, "1" and "0" for "A" and "ph" respectively? If no, then press "n", otherwise, "y"\n: ');
    if (default1==y)
        A = input('enter value for "A": ');
        ph = input('enter value for phase angle: ');
    else
        plot(x,drawFunction,'r','-.'),xlabel('x'),ylabel('y'),legend('sin(x)')
    end
    
end

Error(s)
Code:
which trig. function you want to draw, enter "s" for sin , eneter "c" for cos, and for tan enter "t": s
Error using input
Undefined function or variable 's'.

Error in main_trigno_functions (line 12)
choice = input('which trig. function you want to draw, enter "s" for sin , eneter "c" for cos, and for tan enter "t": ' );
 
Could you please tell me how to combine string and variable values using fprintf? You can use the code given below. Thanks.
I didn't think printf could be used to display matrices natively. You'd have to iterate through the elements. Use disp(A) instead.

To display a single element using fprintf, try fprintf("The value of the first element in A is %g\n", A(1,1));

If you're having trouble with a function, use the help command in the matlab window. e.g. "help disp" will display relevant info about the disp function.

It's not working for me. Where am I going wrong? Please let me know. Thanks.
Sorry, my mistake. Use disp(['here is A(1,1): ' num2str(A(1,1))]);


Could you please tell me what I did wrong? When I press "s" I get an error which is given below.
Please read post 2 and post 15 above. Type "help input" into the matlab command window to get details on how to use the input function. You tried to use the value of the 's' variable, which doesn't exist. Try using input to read and return a string value rather than an expression (see help for how this is done).

example here: n = input('Please enter your name: ', 's'); if(~isempty(n)),fprintf('hello "%s"\n"', n), end
 
Hi

I have been getting the following error for many of the problems. How do I get rid of it? Would you please help me with it? Thank you.

Code:
x=[0:50];
y=3;
stem(x,y);
??? Error using ==> stem at 44
X must be same length as Y.

I don't get an error when I do this:

Code:
x=[-10:10];
y=2*x;
stem(x,y);
 
Last edited:
What are you trying to do?

I assume that with the first code block you wish to plot 51 points each having a y value of 3? Try:
Code:
x = 0:50;
y = 3 * ones(1, length(x));
stem(x, y);

You need to have a y value specified for each x value. In your first example, x is a 1x50 vector and y is a scalar (or 1x1 vector) -- note that 50 elements (x) is different to a single element (y). Basically you have to provide the function with (X, Y) coordinate pairs; i.e. every value in Y must have a corresponding/associated value in X. You can also call the stem function with just a vector of Y values, in which case it will assume the X values to be uniformly spaced (starting at 1 and increasing by 1 each sample).

The reason your second example works is because both x & y have the same number of elements.
 
Last edited:
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top