Problem with "if ~isempty" and "break" in a while loop
Show older comments
Hello I'm running the following code but it seems that in the lines
if ~isempty(cols_withonly0)
col_0=cols_withonly0(1);
else
break
end
the condition ~isempty(cols_withonly0) is not recognized and the "break" in the while loop occurs before filling the pixl_list matrix with non zero values. "fi" and "IM" are 2000*2992 matrix with non zero values. When I run the code without the lines "if ~isempty(cols_withonly0)", "else", "break", "end" the "pixl_list" is filled as I want but I have an error message at the end because "cols_withonly0" is empty and cols_withonly0(1) exceeds array bounds. Do you have an idea where the mistake is and how to fix it to fill the "pixl_list" properly?
Thank you in advance for your answers!
pi_min=round(-pi,1);
pi_max=round(pi,1);
Non0_IM = length(find(nonzeros(IM)));
Non0_pxllist= 0;
N_max=Nx*Ny;
while Non0_IM > Non0_pxllist && pi_min < pi_max
for k=pi_min:0.1:pi_max
pos=(k+round(pi,1))*10+1;
pos=round(pos);
posi(pos)=pos;
ka(pos)=k;
[fila columna]=find(fi==k);
for ind=1: length(fila)
fifi=fila(ind);
coco=columna(ind);
pixl=IM(fifi, coco);
pixl_list (pos,ind)= pixl;
end
end
Non0_pxllist= length(find(nonzeros(pixl_list)));
cols_withonly0=find(all(pixl_list==0));
if ~isempty(cols_withonly0)
col_0=cols_withonly0(1);
else
break
end
pi_min=ka(col_0);
pi_max=pi_min;
end
7 Comments
I've formatted the code to improve the readability.
Please post some test data, e.g. created by rand(). Otherwise we cannot run your code to see, what happens.
Notes:
nnz(IM) % nicer and faster than: length(find(nonzeros(IM)))
The expression "all(pixl_list==0)" is dangerous, if it is not clear if the argument is a matrix or a vector. It is safer to specify the dimension to operate on: all(pixl_list==0, 1)
Martina Clairand
on 26 Jan 2021
Martina Clairand
on 26 Jan 2021
Steven Lord
on 26 Jan 2021
Please set a breakpoint on the line containing that break statement and show us the output of the following command executed when MATLAB stops at that breakpoint:
whos cols_withonly0 pixl_list
Martina Clairand
on 26 Jan 2021
dpb
on 26 Jan 2021
Certainly doesn't seem to be an issue there; it would be beneficial to see a run and the complete error message in context as well.
Just from a stylistic point, the code would be easier to read if it were written as
if isempty(cols_withonly0)
break
else
col_0=cols_withonly0(1);
end
Although as posted the irregularity in the indenting makes the code hard to read; it would seem the above could also be simplified to just
...
if isempty(cols_withonly0), break; end
col_0=cols_withonly0(1);
...
since the remainder of the loop isn't executed anyway.
Martina Clairand
on 27 Jan 2021
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!