MATLAB Answers

0

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

Trevor Hamilton さんによって質問されました 2019 年 5 月 7 日
最新アクティビティ Trevor Hamilton さんによって コメントされました 2019 年 5 月 8 日
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.

  0 件のコメント

サインイン to comment.

タグ

1 件の回答

回答者: James Tursa
2019 年 5 月 8 日
編集済み: James Tursa
2019 年 5 月 8 日

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 件のコメント

Thank you for your answer, but how does MATLAB know what Q1 is if I dont declare it before I index?
When I tried it like this.
H = load('HW3a.mat')
plot(H.Q1(:,1),H.Q1(:,2))
% This returns an error saying
% "Reference to non-existent field 'A1'."
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))
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!

サインイン to comment.



Translated by