How to inherit values from for loop into if else loop?

1 view (last 30 days)
This is my code :
for i=1:n
Area(i)=k(i).Area;
Diameter(i)=sqrt(4*[k(i).Area]/pi);
MajorAxis(i)=k(i).MajorAxisLength;
end
Now I want to use the MajorAxis value into if else loop. Eg :-
if MajorAxis(i) < 0.002
Clay(i)=MajorAxis(i);
end
But the (i) values from for loop are not being inherited.
  3 Comments
Tinna Armasamy
Tinna Armasamy on 25 Apr 2017
Edited: Walter Roberson on 26 Apr 2017
i mean that the i values are not performing the if else loop
Jan
Jan on 25 Apr 2017
This is unclear: "i values not performing the if else loop". I cannot imagine, what this should mean. There is neither an "if else loop", nor do loop counters "perform" anything - most of all not outside the loop.

Sign in to comment.

Answers (1)

Jan
Jan on 25 Apr 2017
There is no magic "inheriting" of loop counters. I think the main problem is hiddon in your formulation "if else loop": The if command is not a loop.
You have to include the if into the loop:
Area = zeros(1, n); % Pre-allocate!
Diameter = zeros(1, n);
MajorAxis = zeros(1, n);
Clay = zeros(1, n);
for i=1:n
Area(i) = k(i).Area;
Diameter(i) = sqrt(4*[k(i).Area]/pi);
MajorAxis(i) = k(i).MajorAxisLength;
if MajorAxis(i) < 0.002
Clay(i) = MajorAxis(i);
end
end
Or you can omit the loop:
Area = [k.Area];
Diameter = sqrt(4 * Area / pi);
MajorAxis = [k.MajorAxisLength];
Clay = zeros(1, n);
Index = (MajorAxis < 0.002);
Clay(Index) = MajorAxis(Index);
  1 Comment
Tinna Armasamy
Tinna Armasamy on 26 Apr 2017
Edited: Walter Roberson on 26 Apr 2017
soilgray=getimage(handles.axes1);
soilgray=rgb2gray(soilgray);
level=graythresh(soilgray);
im=im2bw(soilgray,level);
axes(handles.axes2);
imshow(im);
cc = bwconncomp(im,8);
n= cc.NumObjects;
set(handles.text11,'String',n);
Area = zeros(n,1);
Diameter = zeros(n,1);
MajorAxis = zeros(n,1);
Clay=zeros(1,n);
Silt=zeros(1,n);
Sand=zeros(1,n);
k = regionprops(cc,'Area','EquivDiameter','MajorAxisLength');
for i=1:n
Area(i) = k(i).Area;
Diameter(i) = sqrt(4*[k(i).Area]/pi);
MajorAxis(i) = k(i).MajorAxisLength;
Diameter(i) = (Diameter(i)*25.4)/300;
if Diameter(i) < 0.002
Diameter(i)=Clay(i);
else if Diameter(i) >=0.002 && Diameter(i) < 0.05
Diameter(i)=Silt(i);
else if Diameter(i) >= 0.05 && Diameter(i) < 2
Diameter(i)=Sand(i);
end
end
end
end
NumC = numel(Clay);
ClayPercentage = (NumC/n)*100;
set(handles.text15,'String',ClayPercentage);
NumC = numel(Silt);
SiltPercentage = (NumC/n)*100;
set(handles.text16,'String',SiltPercentage);
NumC = numel(Sand);
SandPercentage = (NumC/n)*100;
set(handles.text17,'String',SandPercentage);
This is what I have done so far. The numel value of Silt, Clay and Sand shows the n value and not the number after performing if else.

Sign in to comment.

Categories

Find more on MATLAB 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!