Home > other >  using variable to define a char in MATLAB
using variable to define a char in MATLAB

Time:08-24

I have a variable

filterSize = 3; %Size of the Filter;

I want to define a new char variable called size and assign it as

size = (filterSize x filterSize)

size='3x3';

but I want to use filterSize to do it to automate. size need to be char. Thanks

CodePudding user response:

You can use sprintf to format a char containing variables

filterSize = 3;
sz = sprintf( '%dx%d', filterSize, filterSize );

You should avoid using size as a variable name because you're shadowing a commonly used in-built function.

CodePudding user response:

I have solved the problem.

size_temp = [string(filterSize),'x',string(filterSize)];
a = convertStringsToChars(size_temp);
size = transpose(char([a(1),a(2),a(3)]));

CodePudding user response:

MATLAB has a function that precisely does what you asked for: .

call generic example :

evalin('base',['output = ',expression])

MATLAB funtion help reference :

https://uk.mathworks.com/help/matlab/ref/evalin.html?s_tid=srchtitle_evalin_1

Assigning a value to new variable within your code has detractors and supporters, as it is a sharp tool that writes new code with code.

I had a couple of bitter discussions with a Mathworks forum member over different ways to use evalin.

When some one preaches not to do something because they call it sinful yet they keep doing it all the time, there's room for doubt that people in general should refrain to use evalin to concisely build new code within existing code.

I recommend you to ignore the last line in evalin help page where some one discourages from using evalin to exactly do what you need to in order to solve your question.

Hope it helps

  • Related