Reputation: 1501
I have a Matlab mat file, which has the following variables:
variable0
variable1
variable2
variable3
Is it possible to dynamically index them and modify, something like this:
function setVariable(obj, variableNum, data)
obj.matFile.(variable0+variableNum) = data;
end
So, if someone passes 0 variable 0 is modified and if someone passes 3 then variable three. I know this code doesn't work, this is just some example of what I tried. My current solution is to use a switch statement. This is not so good as in the C++ code, I am using indexing like above. I would like the C++ and Matlab to be as close as possible.
ANSWER
I did it this way and it is working:
eval(sprintf('obj.matfile_variable%d = data;', variableNum));
Upvotes: 0
Views: 94
Reputation: 13
function setVariable(obj, variableNum, data)
% check if variableNum is numeric
if isnumeric(variableNum)
variableNum = num2str(variableNum);
varName = strcat('variable',variableNum);
else
varName = strcat('variable',variableNum);
end
obj.matFile.(varName) = data;
end
This should do the trick.
Upvotes: 0