Save unique variable after same routine of n loops and output to a table or file?

2 views (last 30 days)
I have a code that takes a .jpg file and performs some pixel analysis functions to it and outputs a floating variable. I want to save this unique variable after looping the routine for n .jpg files in a directory. Then I want to tabulate all of these variables and write them to a file.
Why does the below not allow me to do it?
jpegFiles = fullfile('Users/myfolder/Desktop/thresholding/*.jpg');
for k = 1:length(jpegFiles)
filename = strcat(num2str(k), '.jpg');
if exist(filename, 'file');
fprintf('%s successfully read.\n', filename);
a = imread(filename, 'jpg');
% Calculation functions omitted for brevity
Cov = somefunction;
fprintf('\n%s%.2f\n','Image pixel coverage:',Cov);
%why won't this let me store Cov variables as a matrix? It overrides the previous Covs if I try the below.
for i = 1:k
Cov2 = num2str(Cov); %create string from number
fprintf('The coverage as a string is:',Cov2);
end
%This line forward prints only the last value to file in same dir as image files but I want it to do so for all Covs:
fid = fopen('Output.csv','wt');
fprintf(fid,'%0.4f\n',Cov);
fclose(fid);
end

Accepted Answer

Walter Roberson
Walter Roberson on 28 Aug 2015
You have
for k = 1:length(jpegFiles)
so your "k" is a scalar.
You have
for M = 1:length(k);
Because k is a scalar, length(k) is 1, so you are effectively using
for M = 1:1
The natural immediate reading would be to think that you wanted
for M = 1 : k
but if you do that then you are going to be writing the same unchanged COV matrix to every element of A, since COV does not change in you "for M" loop. This suggest that a "for M" loop is not desirable at that point in the code.
You have
dlmwrite('kerogen coverage.xls',A)
As per the above you only ever write to A{1}, so you will only ever have one output set in the file with your code. You are also always writing to the same file which would keep overwriting that one output set with a new value.
I suspect that what you want is to change
for M = 1:length(k);
A{M} = Cov;
fprintf('\n%s%.2f\n','This value is stored in the percentage coverage matrix:',A{M});
celldisp(A);
end
to
A{k} = Cov;
fprintf('\n%s%.2f\n','This value is stored in the percentage coverage matrix:',A{k});
celldisp(A);
In this way A is going to get larger on each k iteration, and will always include the previous output, so although you overwrite the same file each time, the file will get updated as the run progresses.
You could have a problem if the dlmwrite() fails as you could end up scribbling over everything you have done so far. That is why it is not a good idea to continually write over all of a file.
  2 Comments
Svet Shkolyar
Svet Shkolyar on 28 Aug 2015
Success!! Thank you so much, Walter!!!
Now how do I get the output to be a table in my csv file that is tab separated rather than comma-separated?

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 27 Aug 2015
It does not allow you to do that as a deliberate design decision to reduce the number of times that people use this kind of bad programming technique. Dynamic variable names almost always cause problems and should be avoided whenever possible.
  4 Comments
Svet Shkolyar
Svet Shkolyar on 28 Aug 2015
Edited: Walter Roberson on 28 Aug 2015
jpegFiles = fullfile('Users/myfolder/Desktop/thresholding/*.jpg');
for k = 1:length(jpegFiles)
filename = strcat(num2str(k), '.jpg');
if exist(filename, 'file');
fprintf('%s successfully read.\n', filename);
a = imread(filename, 'jpg');
filename1 = strcat(filename,'_flagged.mat');
red_min = 0;
red_max = 13;
green_min = 0;
green_max = 13;
blue_min = 0;
blue_max = 13;
a = imread(filename);
a_red = a(:,:,1);
a_green = a(:,:,2);
a_blue = a(:,:,3);
ind_flag = find( a_red >= red_min & a_red <= red_max & a_green >= green_min & a_green <= green_max & a_blue >= blue_min & a_blue <= blue_max );
flagged = zeros(size(a_red));
flagged(ind_flag) = 1;
figure
image(uint8(cat(3,255*ones(size(flagged)),255*(ones(size(flagged))-flagged),255*(ones(size(flagged))-flagged))))
figure
image(uint8(a))
save(filename1,'flagged')
%STEP 2
load (filename1)
filename = strcat(filename1,'_particles.mat');
flagged = padarray(flagged,[1,1],0); %Pad the marked pixel array to avoid a different neighbor index algorithm at the edges
ind = find(flagged > 0);
flagged(ind) = Inf;
particles = zeros(size(flagged));
neighbors = zeros(size(flagged));
[m,n] = size(flagged);
neighbors_offset = [m,-m,1,-1,m+1,m-1,-m+1,-m-1];
j = 1;
while( min(size(find(isinf(flagged) == 1))) > 0 )
particles(ind(1,1)) = j; %Save index location
flagged(ind(1,1)) = 0; %Unmark pixel
neighbor_indices = bsxfun(@plus,ind(1,1),neighbors_offset);
neighbors(neighbor_indices) = 1;
ind_neighbors = find(isinf(neighbors.*flagged) > 0);
neighbors(neighbor_indices) = 0;
while( min(size(ind_neighbors)) > 0 ) %While you have neighbors to check
particles(ind_neighbors) = j;
flagged(ind_neighbors) = 0;
neighbor_indices = bsxfun(@plus,ind_neighbors,neighbors_offset);
neighbors(neighbor_indices) = 1;
ind_neighbors = find(isinf(neighbors.*flagged) > 0);
neighbors(neighbor_indices) = 0;
end
neighbors = 0*neighbors;
j = j+1;
ind = find(flagged > 0); %Update the to-be-checked list
end
particles = particles(2:end-1,2:end-1); %Remove the padding
save(filename,'particles');
figure
pcolor(particles);
shading interp
load(filename)
filename = strcat(filename1,'_particles_filtered.mat');
particle_threshold = 2; %The minimum area, in pixels, to be considered a grain. Everything below this size is discarded.
num_particles_before = max(particles(:)); %Number of particles before filtering
num_particles_after = 0; %Number of particles after filtering
particles_after = zeros(size(particles)); %Storage for filtered particles
for j = 1:num_particles_before
ind = find(particles == j);
if( max(size(ind)) > particle_threshold )
num_particles_after = num_particles_after+1;
particles_after(ind) = num_particles_after;
end
end
save(filename,'particles_after');
ind = find(particles > 0);
particles(ind) = 1;
ind = find(particles_after > 0);
particles_after(ind) = 1;
figure
image(uint8(cat(3,255*ones(size(particles)),255*ones(size(particles))-255*particles,255*ones(size(particles))-255*particles)));
figure
image(uint8(cat(3,255*ones(size(particles)),255*ones(size(particles))-255*particles_after,255*ones(size(particles))-255*particles_after)));
figure
image(a)
load (filename1); %Generated from step3.m
num_particles = max(particles_after(:)); %Total number of particles
size_of_particles = zeros(1,num_particles); %Size of each, in pixels
for j = 1:num_particles
ind = find(particles_after == j);
size_of_particles(1,j) = max(size(ind));
end
average_size = mean(size_of_particles);
var_of_size = var(size_of_particles);
percentage_of_slide = sum(size_of_particles)/prod(size(particles_after));
Cov = 100 - 100*percentage_of_slide;
fprintf('\n%s%i%s\n','There are ',num_particles,' total particles')
fprintf('\n%s%.2f%s\n','The average size is ',average_size,' pixels')
fprintf('\n%s%.2f%s%.2f\n','The size has variance ',var_of_size,' and standard deviation ',sqrt(var_of_size))
fprintf('\n%s%.2f\n','Kerogen coverage:',Cov);
%Creating a matrix of Covs but they keep getting overwritten!
for M = 1:length(k);
A{M} = Cov;
fprintf('\n%s%.2f\n','This value is stored in the percentage coverage matrix:',A{M});
celldisp(A);
end
dlmwrite('kerogen coverage.xls',A)
else
% No else statement needed.
end
end

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!