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

1 次查看(过去 30 天)
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!

采纳的回答

Philip Borghesani
Philip Borghesani 2016-1-29
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 个评论
aacarey
aacarey 2016-1-29
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by