Error when function changes cell array size
2 views (last 30 days)
Show older comments
I have the following function,
function args = updateCell(args, string, value)
% args = updateCell(args, string, value) Takes a cell array, args,
% presumably name / value pairs, and updates the value of the next cell
% after the cell containing the string with value. i.e. changes the
% value for that name/value pair. If pair isn't present, it is appended.
if isempty(find(strcmp(args,string),1))
args(length(args)+1) = string;
args(length(args)+1) = value;
else
ind = find(strcmp(args,string));
if length(ind) > 1
error(['multiple instances of ' string 'value in args'])
return
end
args(ind+1) = value;
end
All the function does is take a cell array, check if the array has a particular string. If it does, update the next cell with the value provided. If it does not have that string, it is supposed to append the cell array with the string and value pair in new, consecutive cells.
Changing the value of an existing string/value pair works with no problem. For example if
args{1} = 'string'; args{2} = 1;
updateCell(args,'string',2)
ans =
'string' [2]
However, if I try to append a new set of values I get this error,
updateCell(args,'string1',10)
The left hand side is initialized and has an empty range of indices.
However, the right hand side returned one or more results.
Error in updateCell (line 8)
args{ind+1} = value;
I know I can use varargout to group returned values into an array but that gives me a nested cell array structure that I don't want. If I embed the code directly in higher level functions it works just fine, but I'd like this as a separate function. I'm running Matlab R2015a (8.5.0.197613).
Is there anyway just to append cells to the array and return the array? Thanks!
3 Comments
Accepted Answer
Guillaume
on 4 Jun 2015
If the error message is the one you posted and the file you're editing is also the one you posted, then matlab is not running that file.
What does
which updateCell
return? You must have another updateCell.m somewhere in your path.
2 Comments
More Answers (1)
Nobel Mondal
on 4 Jun 2015
You ought to be using curly brackets for indexing here.
function args = updateCell(args, string, value)
if isempty(find(strcmp(args,string),1))
args{end+1} = string;
args{end+1} = value;
else
ind = find(strcmp(args,string));
if length(ind) > 1
error(['multiple instances of ' string 'value in args'])
end
args{ind+1} = value;
end
This code seems to be working fine for me - wasn't able to reproduce the error you showed.
>> myVar = {};
>> myVar = updateCell(myVar, 'First', 1)
myVar =
'First' [1]
>> myVar = updateCell(myVar, 'Second', 2)
myVar =
'First' [1] 'Second' [2]
>> myVar = updateCell(myVar, 'First', 10)
myVar =
'First' [10] 'Second' [2]
See Also
Categories
Find more on Characters and Strings 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!