Search code examples
matlabfor-loopevalcellprintf

In matlab, when I used eval and sprintf (variable%d), why can't the line containe two different variables that utilize %d?


Here's an example:

for b = 1:numcarlo;
eval(sprintf('pspsdist%d = psdistmat(b,:);', b))
eval(sprintf('cell%d = cell(1, iterestemp%d);', b))
end;

Line 1 works, it tells us how many times to execute in the for loop. Line 2 works, it generates numcarlo numbers of pspsdist with the number as a suffix (pspsdist1, etc). Line 3 doesn't work as long as iterestemp has a %d at the end. It provides the following error:

??? Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

But it's balanced! When I get rid of that %d, it works, but I need to have iterestemp%d because there are multiple iterestemps with suffixes (as in pspsdist, they are numbered at the end and I refer to a specific one).

Why does matlab do this and is there any way around this?


Solution

  • Each %d needs its own argument. Try this:

    eval(sprintf('cell%d = cell(1, iterestemp%d);', b, b))
    

    (But really you should be using arrays of some sort. I'd like to give more specific advice but I don't really know Matlab.)