Clear Filters
Clear Filters

Error "Matrix index is out of range for deletion" with dynamic variable names but not hardcoded names?

1 view (last 30 days)
I get the error for the following case using dynamic variables:
% some things I pulled out of my data for the example:
arms = {'L','R'};
fields.L = [17 8 12 16];
fields.R = [12,6];
[~,removeL,removeR] = intersect(fields.L,fields.R);
uniquefields = fields;
% loop through arms (errors here)
for iArm = 1:length(arms)
uniquefields.(arms{iArm})(['remove',arms{iArm}]) = [];
end
But it doesn't happen when I hardcode it:
uniquefields.L(removeL) = [];
uniquefields.R(removeR) = [];
Does anyone know how to fix it? Thanks for any help!

Accepted Answer

Philip Borghesani
Philip Borghesani on 29 Jan 2016
The code blocks are not doing the same thing. Your loop is doing:
uniquefields.('L')('removeL') = []
It could be fixed with an eval of the string but that is going in the wrong direction. I suggest trying this sequence:
arms = {'L','R'};
fields.L = [17 8 12 16];
fields.R = [12,6];
[~,remove{1},remove{2}] = intersect(fields.L,fields.R);
uniquefields = fields;
% loop through arms
for iArm = 1:length(arms)
uniquefields.(arms{iArm})(remove{iArm}) = [];
end
There are probably much better solutions for your final code I don't much like needing a list of field names to be used dynamically.
  1 Comment
aacarey
aacarey on 29 Jan 2016
Thank you! I didn't realize that my variable was just staying as a string. This is part of a larger structure with a lot of data. I like keeping my data in large branching structures because the organization of fields is more understandable to me than keeping separate arrays. The fields become kind of "human readable" in the end.

Sign in to comment.

More Answers (0)

Categories

Find more on Multidimensional Arrays 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!