Insert variable into string

  • Follow


Say I want to display: 
"I am 10 years old"
"I am 11 years old"
....
"I am 30 years old"
So I could put a for loop from 10 to 30 like:
for n=10:1:30
disp('I am <n> years old') 
end

How do I put the value of n into my string?
Cheers
0
Reply Chris 9/1/2010 5:24:05 AM

"Chris " <chris.taeni@gmail.com> wrote in message <i5ko1l$pns$1@fred.mathworks.com>...
> Say I want to display: 
> "I am 10 years old"
> "I am 11 years old"
> ...
> "I am 30 years old"
> So I could put a for loop from 10 to 30 like:
> for n=10:1:30
> disp('I am <n> years old') 
> end
> 
> How do I put the value of n into my string?
> Cheers

 disp(['I am ' num2str(n) ' years old']) 
0
Reply Grzegorz 9/1/2010 6:27:34 AM


Use sprintf()

for n=10:1:30
    outputString = sprintf('I am %d years old', n)
end
0
Reply ImageAnalyst 9/1/2010 10:23:01 AM

ImageAnalyst <imageanalyst@mailinator.com> wrote in message <384e9858-b5ae-4538-89c1-748afef5798e@t20g2000yqa.googlegroups.com>...
> Use sprintf()
> 
> for n=10:1:30
>     outputString = sprintf('I am %d years old', n)
> end

Why you propose sprintf? Is this better solution that disp?
0
Reply Grzegorz 9/1/2010 10:41:25 AM

I've just always preferred sprintf() because it gives you much more
control, like the field width, how many decimal places, whether you
want multiple lines in the string, etc.  And it's what people are
already familiar with from their days with C++.  But for simple
strings, they're pretty equivalent ways of doing it.
0
Reply ImageAnalyst 9/1/2010 10:44:43 AM

Dear Chris,

> Say I want to display: 
> "I am 10 years old"
> "I am 11 years old"
> ...
> "I am 30 years old"
> 
> for n=10:1:30
>    disp('I am <n> years old') 
> end

And you can even vectorize it as experienced Matlab cracks would do:
  fprintf('I am %d years old\n', 10:30);

While SPRINTF writes to a string, FPRINTF writes to files. But FPRINTF(1, ...) or just FPRINTF(...) writes to the command window.

Good luck and welcome to Matlab, Jan
0
Reply Jan 9/1/2010 12:05:19 PM

5 Replies
582 Views

(page loaded in 0.58 seconds)

Similiar Articles:













7/22/2012 9:01:56 AM


Reply: