How can I handle the "Index exceeds matrix dimensions error" by programming?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2017-12-31
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!