Clear Filters
Clear Filters

Problem with sprintf and evalin

3 views (last 30 days)
Maine MacConville
Maine MacConville on 1 Mar 2016
Edited: Stephen23 on 1 Mar 2016
I'm trying to import 40 CR2 images (Canon camera) for flat and dark field correction. The image file names are of the form IMG_1234. The images come in two sets, so I have the following code:
_
for j = 3929:3948 evalin('base', sprintf('[ dark_%d ] = imread(IMG_%d.CR2);', j-3928, j)); end
for i = 291:310 evalin('base', sprintf('[ flat_%d ] = imread(IMG_0%d.CR2);', i-290, i)); end
---
But I'm getting the error message:
_
Undefined variable "IMG_3929" or class "IMG_3929.CR2".
Error in DarkFlat (line 6) evalin('base', sprintf('[ dark_%d ] = imread(IMG_%d.CR2);', j-3928, j));
_
This file exists and Matlab has no problem importing CR2 files via imread (I've checked this manually). What have I done wrong?

Answers (2)

Stephen23
Stephen23 on 1 Mar 2016
Edited: Stephen23 on 1 Mar 2016
"What have I done wrong?"
You decided to use evalin.
Poor choice of programming tools makes your code buggy, as you are finding out. When people write code with slow, buggy, and obfuscated tools (like evalin), then clearly their code will be slow, buggy and obfuscated. Learn to pass your variables properly and your code will not be buggy and slow. It really is that simple.
Read this, and all of its links:
and also this:
You chose to ignore the "Best Practice: Passing Arguments" and instead used the least recommended method of passing information between workspaces (both evalin and assignin), the ones at the bottom of the page with a warning "Use them sparingly."
And now the bugs are starting to show....

Adam
Adam on 1 Mar 2016
Edited: Adam on 1 Mar 2016
I have never used evalin and hope never to do so, but it looks like you are missing quotation marks from around your IMG_0%d.CR2 inside imread.
Once your string gets evaluated your version will have that simply being considered a variable which, as it quite rightly says, does not exist.
evalin('base', sprintf('[ flat_%d ] = imread(''IMG_0%d.CR2'');', i-290, i));
is what I think you need instead if you really insist on using evalin.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!