0

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));
3
  • Do yo mean sprintf('variable%d',variableNum)? Commented Nov 30, 2016 at 6:43
  • But how can I use a string to call the mat file? Commented Nov 30, 2016 at 6:49
  • Do you mean how to use the string to load the mat file into a Matlab object? If so, you need matfile(filename) function to create an matfile object. And honestly, I don't think it would be working in just one line. You perhaps need some data checking as well. Commented Nov 30, 2016 at 14:56

2 Answers 2

0
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.

Sign up to request clarification or add additional context in comments.

1 Comment

I know it's trivial but I'd like to mention. num2str actually checks the first input argument for string type and return it directly. so you don't need the if...else... statement. Just do the conversion and string concatenation.
0

What about using

obj.matFile(variableNum).data = data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.