Effacer les filtres
Effacer les filtres

How can I handle the "Index exceeds matrix dimensions error" by programming?

4 vues (au cours des 30 derniers jours)
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())?

Réponse acceptée

Walter Roberson
Walter Roberson le 31 Déc 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.

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by