Dynamic Variables in Loops
Show older comments
I'm sure this has been answered before, but I can't seem to find the answer anywhere... Pretty simple problem for seasoned MATLAB users...
I have a series of images in a folder. I am trying to average these images. I start off by prompting the user for a folder to work from, then count the number of .jpg's in the folder. I run a loop to create a variable A for each image in the folder (A1, A2, A3, ....., A(i))
Now I need to assign those images to A(i) for them to processed.
Here is the code, thanks in advance. It is NOT recognizing A(i) (I think) and the error message is
Error in Average_Code (line 21) A(i)=imread(Files(i).name);
clc;
clear all;
close all;
%User selecting image directory
cd(uigetdir);
%Counting number of .JPG's in folder
Files = dir('*.jpg')
b=numel(Files);
%Create Dynamic Variables
for i=1:b
eval(['A' num2str(i) '= i']);
end
fusion = 0;
%Assign Images to Dynamic Variables
for i=1:b
A(i)=imread(Files(i).name);
A(i)=double(A(i));
fusion = fusion + A(i);
end
%Average Images
average_image = fusion/b;
imshow(average_image);
Thoughts?
1 Comment
Stephen23
on 30 Oct 2014
The answer is simple: do not do this. In MATLAB it is (almost always) better to not create variable names on the fly:
Alternatives usually involve accumulating data in an array (which could be a struct or cell), of course with array preallocation. This page gives excellent examples about how you can do this:
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!