In Matlab can I directly modify a value in a containers.map when the value is the element of an array?

13 views (last 30 days)
I'm wondering if this syntax is possible? Specifically, I want to increment the first element of the array which is the number 3, cooresponding to the first value that the key 'Li' points to. Specifically, I'm asking about the line "M('Li')(i) = M('Li')(i) + 1"
keySet = {'Li','Jones','Sanchez'};
testLi = [3 4 5];
testJones = [27 3.92 6.4 8.21];
testSanchez = 'C:\Tests\Sanchez.dat';
valueSet = {testLi,testJones,testSanchez};
M = containers.Map(keySet,valueSet,'UniformValues',false)
M('Li')(i) = M('Li')(i) + 1
I know this doesn't work, it throws an error. Can this be done without code that looks like this:
hold = M('Li')
hold(1) = hold(1) + 1
M('Li') = hold

Accepted Answer

Adam Danz
Adam Danz on 4 Dec 2019
You could add a local function at the bottom of the m-file that does the dirty work.
M = plusOne(M,'Li',i);
function mapObj = plusOne(mapObj,key,idx)
% This function merely adds 1 to mapObj(key)(idx)
% INPUTS
% mapObj is the handle to the map container
% key is a char array naming the key
% idx is a positive integer identifying which value to add one to
v = zeros(size(mapObj(key)));
v(idx) = 1;
mapObj(key) = mapObj(key) + v;
end % 'end' may or may not be needed

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!