How can I handle the "Index exceeds matrix dimensions error" by programming?
2 views (last 30 days)
Show older comments
K M Ibrahim Khalilullah
on 31 Dec 2017
Answered: Walter Roberson
on 31 Dec 2017
I have stored data in a structured variable, like this:
data(1).pp(1,:)=[3 4];
data(3).pp(1,:)=[3 4];
but the index 2 is free from data. when I am going to access data(1).pp or data(3).pp , then it is ok. But when I am going to access data(2).pp, it gives the error. Is there any function to handle the index exceeds matrix dimension error in run time by programming like a empty matrix (isempty())?
0 Comments
Accepted Answer
Walter Roberson
on 31 Dec 2017
1) Yes, you can use
if isempty(data(DATA_INDEX).pp)
before attempting to index data(DATA_INDEX).pp(PP_INDEX,:)
2) Instead, you could make sure that you have something stored there, such as storing nan or inf or 0 of appropriate size first before setting the specific elements. You might want to take advantage of the fact that when you use struct() and give a cell array of values, then the different members of the cell array are stored into different struct indexes:
data = struct('pp', repmat( {nan(5,2)}, 4, 1 }) )
to get data(1) through data(4) with field pp initialized to nan(5,2) for each of the data()
3) If for some reason you do not have control over some references but you want to make sure the program handles the situation nicely, then you could use try/catch blocks.
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!