Judith Nelson-Spanks
Judith Nelson-Spanks

Reputation: 31

sprintf in MATLAB

How can I display the value of a variable inside the sprintf function in MATLAB? For example, I need to display

This variable has the type char and the value 'whatever'.

My code looks like this so far:

function [desInput] = varInfo (numVec)  

cLass = class(numVec);  
var1 = num2str(numVec);  
desInput = sprintf('This variable is of class %s and has a value of ''%d''.', cLass, var1);       

end 

It isn't quite working right.

Upvotes: 0

Views: 1463

Answers (2)

rayryeng
rayryeng

Reputation: 104565

sprintf generates a string of a desired formatting and places it into a variable. If you want to display it, either use fprintf, or use disp(desInput); on your created string when using sprintf.

Also, you want to display the value numVec, but you are converting it to a string before display. As such, either remove the num2str call, or use %s as the modifier when displaying your number.

Therefore, do either this:

function [desInput] = varInfo (numVec)

cLass = class(numVec);
desInput = sprintf('This variable is of class %s and has a value of ''%d''.', cLass, numVec);
disp(desInput);

end

OR

function [desInput] = varInfo (numVec)

cLass = class(numVec);
fprintf('This variable is of class %s and has a value of ''%d''.\n', cLass, numVec);

end

OR

function [desInput] = varInfo (numVec)

cLass = class(numVec);
var1 = num2str(numVec);
desInput = sprintf('This variable is of class %s and has a value of ''%s''.', cLass, var1);
disp(desInput);

end

OR

function [desInput] = varInfo (numVec)

cLass = class(numVec);
var1 = num2str(numVec);
fprintf('This variable is of class %s and has a value of ''%s''.\n', cLass, var1);
disp(desInput);

end

Notice that in the fprintf solution, I insert a newline so that the command prompt >> goes underneath your text when displayed.

Upvotes: 1

VHarisop
VHarisop

Reputation: 2826

num2str produces a string representation. You should use %s for it as well.

To see the difference:

N = 65; % random example
fprintf('%d\n', num2str(N)); % produces 5453
fprintf('%s\n', num2str(N)); % produces 65

Upvotes: 0

Related Questions