Search code examples
matlabplotmatlab-figurematlab-guide

plot from file in matlab


robot4_motors.txt

M 204 20795 20795 3000 0 16067 16066 3000 0 0 0 6000 0
M 524 20795 20794 3000 0 16067 16066 3000 0 0 0 6000 0
M 735 20795 20795 3000 0 16067 16066 3000 0 0 0 6000 0
M 995 20795 20795 3000 0 16067 16067 3000 0 0 0 6000 0
M 995 20795 20795 3000 0 16067 16067 3000 0 0 0 6000 0
M 1233 20795 20795 3000 0 16067 16067 3000 0 0 0 6000 0
M 1499 20795 20795 3000 0 16067 16067 3000 0 0 0 6000 0
M 1763 20795 20795 3000 0 16067 16067 3000 0 0 0 6000 0

This is a data file. I want to take out 3rd column and 7th column from the file and plot them as well. I write down the code in matlab.

Code

f = fopen('robot4_motors.txt');
plot(f(:, 3), f(:, 7))

But the code did not work .

Throws error Index in position 2 exceeds array bounds (must not exceed 1).

Error in trick1 (line 21) plot(f(:, 3), f(:, 7))


Solution

  • fopen returns a numeric id which refers to the opened file, it's not a matrix. You need to parse the file to extract the data.

    One way to parse the file is to use dlmread since this is a space delimited file.

    % Read data into M starting at row 0, column 1.
    M = dlmread('robot4_motors.txt', ' ', 0, 1);
    

    After this, M will contain all the entries from the file except the first column (which aren't numeric).

    >> M
    M = 
         204       20795       20795        3000           0       16067       16066        3000           0           0           0        6000           0
         524       20795       20794        3000           0       16067       16066        3000           0           0           0        6000           0
         735       20795       20795        3000           0       16067       16066        3000           0           0           0        6000           0
         995       20795       20795        3000           0       16067       16067        3000           0           0           0        6000           0
         995       20795       20795        3000           0       16067       16067        3000           0           0           0        6000           0
        1233       20795       20795        3000           0       16067       16067        3000           0           0           0        6000           0
        1499       20795       20795        3000           0       16067       16067        3000           0           0           0        6000           0
        1763       20795       20795        3000           0       16067       16067        3000           0           0           0        6000           0