Why am I receiving this error "Index in position 2 exceeds array bounds (must not exceed 1)."

1 view (last 30 days)
Q1 = load('HW3a.mat')
% This data is 100x2
plot(Q1(:,1),Q1(:,2)) % This line of code returns the error in the title.
Why is it that I am recieving this error? I apologize I am a MATLAB Newbie.

Answers (1)

James Tursa
James Tursa on 8 May 2019
Edited: James Tursa on 8 May 2019
When you load into a variable, the data loads into a struct. The fieldnames of that struct are the variables in the mat file. So you need to do something like this instead:
H = load('HW3a.mat'); % loads into a struct named H
plot(H.Q1(:,1),H.Q1(:,2)) % The Q1 field of struct is the Q1 variable from mat
The way you are currently doing it, MATLAB thinks you are trying to index into the struct itself which is a 1x1 struct, hence the error message.
  3 Comments
Walter Roberson
Walter Roberson on 8 May 2019
Like James pointed out, the name you subreference would be the same as the name of the variable as stored in the .mat file. If the name of the variable in the .mat file is Homework3_signal0593 then you would refer to H.Homework3_signal0593
If you do not know the names of the variables in the .mat file, then you can examine them by
whos -file HW3a.mat
Sometimes it is necessary to be able to load variables from .mat files when the names of the variables are not reasonably known ahead of time, or when the names of the variables are the same as the names of the .mat files. It is possible to program for this, using dynamic field names:
varnames = fieldnames(H);
var1name = varnames{1};
H1 = H.(var1name);
plot(H1(:,1), H1(:,2))
Trevor Hamilton
Trevor Hamilton on 8 May 2019
Thank the code ended up working when I ran it as such. Your input helped and James, helped a lot. I've never seen it so complicated, i usually load frome excel files or txt files and have never ran into this struct issue of file referencing.
%% Plot data from HW3a.
% The data in HW3a is 100x2 matrix, referenced in struct.
H = load('HW3a.mat')
plot(H.HW3a(:,1),H.HW3a(:,2))
Thank you!

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!