While loop for the elements of an array
50 次查看(过去 30 天)
显示 更早的评论
I have an array:
a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3];
I want to make a while loop that does the following
enas=0;
while a(i)==1 %
enas=enas+1;
end
But I don't know how to express it in matlab. Can you help me please?
1 个评论
采纳的回答
Image Analyst
2013-5-27
Here's how you'd do it:
a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3];
enas=0;
k = 1;
while a(k)==1 %
enas=enas+1
k = k + 1
end
But here's how a real MATLAB programmer would do it:
enas = find(a~=1, 1, 'first')-1
3 个评论
Image Analyst
2013-5-27
If you need to count the length of each stretch of 1's in your array, and if you have the Image Processing Toolbox, you'd do this:
measurements = regionprops(a==1, 'Area');
allLengths = [measurements.Area]; % Get lengths of all stretches of 1s.
If you don't have the Image Processing Toolbox, it's more difficult - let me know if you have that unfortunate case.
更多回答(1 个)
Jason Nicholson
2013-5-27
See the lines below. This will work.
a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3];
i = 1;
enas=0;
while a(i)==1 %
enas=enas+1;
i = i +1;
end
4 个评论
Matt Kindig
2013-5-27
编辑:Matt Kindig
2013-5-27
This should do it:
b = [0, a, 0]; %ensure that ends are not 1
edges = find(b~=1); %location elements that are not 1
spans = diff(edges)-1; %distance between edges is span of 1's
enas = spans(spans~=0) %should output 7 6 4
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!