Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: EVAL within EVAL
Date: Mon, 2 Nov 2009 11:52:02 +0000 (UTC)
Organization: Universit&#228;t Heidelberg
Lines: 28
Message-ID: <hcmh52$5ig$1@fred.mathworks.com>
References: <hclda3$slq$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1257162722 5712 172.30.248.38 (2 Nov 2009 11:52:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Mon, 2 Nov 2009 11:52:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869888
Xref: news.mathworks.com comp.soft-sys.matlab:581785


Dear Ariel!

I really recommend to find a better way than EVAL. E.g. use a struct with the field names 'x1', 'x2' etc:
  for i = 1:10
    name = sprintf('x%d', i);
    S.(name) = S.(name) * 3;
  end

If all vectors have the same size, better use a Matrix to store them.
If the vectors have different length, a cell is much better than EVAL.

Anyway. You asked for:

> for i = 1: 10
>   eval(['x' num2str(i) ' = eval(['x' num2str(i) ' ']) * 3']);
> end

This would work as:
 for i = 1: 10
   eval(['x', sprintf('%d', i), ' = x', sprintf('%d', i), ' * 3']);
 end

SPRINTF is faster than NUM2STR. But if you start to use it, your EVAL line can be even simplified:
 for i = 1: 10
   eval(sprintf('x%d = x%d * 3', i, i));
 end

But, as said alread, non-EVAL methods are better, Jan