7
$\begingroup$

I am trying to create a string of the form

$0 < d_1 < d_2 < \ldots < d_n$

For a given n.

My closest attempt so far is

eqn[n_] := For[i = 1; str = "0", i <= n, i++, str = str <> "<" <> ToString[Subscript[d, i]]]; 

But for, say n=6, this gives me

"0<d 1<d 2<d 3<d 4<d 5<d 6" 

Where it seems to have interpreted the string as "0<d\n 1<d\n 2<d\n 3<d\n 4<d\n 5<d\n 6".

Why is it doing this? How can I achieve the result I am looking for?

$\endgroup$
2
  • 3
    $\begingroup$ Use ToString[..., StandardForm]. $\endgroup$ Commented Jul 23, 2013 at 10:31
  • $\begingroup$ If you just need this for display purposes, you can also use StringForm $\endgroup$ Commented Oct 26, 2020 at 18:03

3 Answers 3

8
$\begingroup$

Probably best to use something like Fold and get used to functional style

eqn[n_] := TraditionalForm[Fold[#1 <> " < " <> ToString[Subscript[d, #2], StandardForm] &, "0", Range[n]]] 

enter image description here

$\endgroup$
2
  • 1
    $\begingroup$ @JacobAkkerboom The first use of ToString is unnecessary actually. I'll make an edit $\endgroup$ Commented Jul 23, 2013 at 11:40
  • $\begingroup$ Okido, +1 and deleting my comment :). $\endgroup$ Commented Jul 23, 2013 at 11:55
5
$\begingroup$

Here's my entry:

string[n_] := ToString[0 < ## & @@ Array[Subscript[d, #] &, n], StandardForm] string[7] 

enter image description here

This assumes that none of the Subscript[d, _] expressions are assigned.

Here is a different method converting to strings as early as possible, using the single-argument form of Subscript:

string2[n_] := "0" <> Array[" < d" <> ToString[Subscript@#, StandardForm] &, n] 

The spacing is a bit wider with this one. You could use narrower spaces, e.g.:

string2[n_] := "0"<>Array["\[MediumSpace]<\[MediumSpace]d"<>ToString[Subscript@#,StandardForm]&, n] 

One more, quite concise:

string3[n_] := "0" <> Array[" < \!\(d\_" <> ToString@# <> "\)" &, n] 
$\endgroup$
3
$\begingroup$

Most important thing is what b.gatessucks has said. This answer is just a variation of the method:

eq[0] = "0"; eq[n_] :="0 < " <> StringJoin @@ Riffle[ToString[Subscript[d, #], StandardForm] & /@ Range[n], " < "] 

If you do not need string but an expression which looks like this, then it is good to remember Row's 2nd argument:

Row[{"0"}~Join~(ToString[Subscript[d, #], StandardForm] & /@ Range[4]), " < "] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.