ONION
ONION

Reputation: 269

How to use sprintf in MATLAB

this is my code

for k = 1 : 5
im = imread(sprintf('C:\1\%d.BMP',k));

%blablalba...

end

There are 5 BMP files in "C: \ 1 \"

The files are named 1.BMP, 2.BMP, 3.BMP, 4.BMP, and 5.BMP respectively

Use sprintf to import files of 1.BMP, 2.BMP ... 5.BMP respectively into imread

But there is an error.

error : demo_SR (line 5)

im = imread(sprintf('C:\1\%d.BMP',k));

Why do I get an error when I get k from 1 to 5 and write"%d"?

thanks you

Upvotes: 0

Views: 562

Answers (2)

Phil Goddard
Phil Goddard

Reputation: 10762

For the reason mentioned in @Ander Biguri's answer, you should either use a double backslash,

filename = sprintf('C:\\1\\%d.BMP',k);

or, more robust would be to let MATLAB insert the appropriate path separator by using fullfile,

filename = fullfile('C:','1',sprintf('%d.BMP',1));

Upvotes: 2

Ander Biguri
Ander Biguri

Reputation: 35525

Try:

im = imread(sprintf('C:/1/%d.BMP',k));

MATLAB may interpret \ as a command for escaped characters.

Upvotes: 2

Related Questions