using variable to define a char in MATLAB

Viewed 46

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

3 Answers

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.

I have solved the problem.

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

but as cris Luengo suggests in the comments size = [num2str(filterSize),'x', num2str(filterSize)] is a better solution

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