简体   繁体   中英

Indentation in latex algorithmic

How is it possible to indent lines in an algorithm (algorithmic) in latex?

I would like to be able to write the following:

\begin{algorithm}[H]
\caption{My Awesome Program} \label{awesome-algorithm}
\begin{algorithmic}[1]
\FOR { $i=0$ to $logn$ } 
    \STATE Step A:
        % would like the indent the next lines...
        \STATE do something
        \STATE do another thing
    \STATE Step B
\ENDFOR
\end{algorithmic}
\end{algorithm}

How is it possible to indent those lines? I've been trying to find the answer by googling without success. I hope you guys can help me. Thanks.


I'm currently using the following for indentation:

          \STATE  \ \ \ \ do something

which seems plain wrong. But works.

Try this instead:

\STATE\hspace{\algorithmicindent} do something
\STATE\hspace{\algorithmicindent} do another thing

It should work better because it uses the current indent value to indent.

Edit : Using Charles's suggestion, you could define a new command, \\INDSTATE :

\newcommand{\INDSTATE}[1][1]{\STATE\hspace{#1\algorithmicindent}}

and then use that when you want indentation. By default, \\INDSTATE indents by one level, but you can change it:

\INDSTATE do something % What you want
\INDSTATE[2] do something % Indent by twice the amount

I would suggest you don't indent that way. The package is designed to format pseudocode in a standard way to make it easier for your readers.

You are trying to break that standard. It would be much better for to try to rewrite the code to conform to what readers expect.

Why are you labeling step A and B, anyway? Each statement is supposed to be its own step. It seems like you are adding extra structure that actually makes the code less readable. Can you get the same effect with comments? How about combining "do something" and "do another thing" into one statement?

I couldn't get Alok's working, so I wrote this:

% Put in preamable:
\usepackage{forloop}
\newcounter{ct}
\newcommand{\markdent}[1]{\forloop{ct}{0}{\value{ct} < #1}{\hspace{\algorithmicindent}}}
\newcommand{\markcomment}[1]{\Statex\markdent{#1}}

Then, to put "This is my comment" at indentation level 3:

\markcomment{3}{"This is my comment"}

Edit: I use algoritmicx (therefore \\State and not \\STATE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM