How do I get the Character Vector "Name" to display within the text in the fprintf statement?
3 views (last 30 days)
Show older comments
Livio Campanotto
on 3 Mar 2018
Commented: Livio Campanotto
on 3 Mar 2018
I am pretty new to matlab coding so I apologize in advance for my crude code lol. I am having some trouble trying to get the name that was input to be displayed with the question of "How much do you make per year, Name?"
Name = input('Hello, What is your name?','s');
disp('Hi,');
disp(Name)
Age = input('What is your age?');
if Age <= 100
fprintf('Your%3.0f thats not that old!\n',Age)
end
Salary = input('How much do you make per year?\n',Name);
if Salary < 15000
fprintf('You need to get a better paying job!\n')
else Salary >= 15000;
fprintf('Thats not to bad...\n');
end
0 Comments
Accepted Answer
Walter Roberson
on 3 Mar 2018
Salary = input(['How much do you make per year, ',Name, '?']);
or
Salary = input( sprintf('How much do you make per year, %s?', Name) );
3 Comments
Walter Roberson
on 3 Mar 2018
['A', Name, 'B'] is the same as horzcat('A', Name, 'B') which just slams the literal characters and the content of Name together into an array without any interpretation of the content at all. This works fine for pure text, but it does tend to get harder to read as a single operation as you start putting more parts together.
sprintf('A %s B', Name) on the other hand groups all of the important parts of the phrase together in one place, by way of a template that tells how input variables are to be converted into text. %s means to copy in a string (character vector) at that point, but you can use other template elements easily. For example,
Salary = input( sprintf('Now that you are %d years old, how much money do you make per year, %s?', Age, Name) );
here the %d template says to expect a numeric value on input and to convert it into the form of a decimal number (integer). The equivalent using [] would look like
Salary = input( ['Now that you are ', num2str(Age), ' years old, how much money do you make per year, ', Name, '?'] )
These accomplish the same thing but the sprintf() version makes it easier to see at a glance how the output is going to come out because the template is not broken up by the details of how to convert the individual parts. The sprintf() version is more efficient when there are numbers to be converted, and is highly recommended if you need fine control over how the output is to look; the [] version is more efficient (but less readable) if you are just slamming character vectors together.
More Answers (0)
See Also
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!