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
Image Analyst 2013 年 5 月 27 日
It's recommended not to use i (the imaginary variable) as a variable name.

サインインしてコメントする。

 採用された回答

Image Analyst
Image Analyst 2013 年 5 月 27 日

0 投票

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 件のコメント

Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 27 日
編集済み: Giorgos Papakonstantinou 2013 年 5 月 27 日
Thank you Image. What if also have to count the in between ones?
Image Analyst
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.
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 27 日
Unfortunately I don't. I just do:
a=[1 1 1 1 1 1 1 10 1 1 1 1 1 1 12 1 1 1 1 3];
enas = find(a~=1)-1
segments=zeros(length(enas),1);
segments(1,1)=enas(1);
segments(2:end,1)=diff(enas)-1;
segments
which a bit complicated but it does the job... If you have better ideas tell me. thank you!

サインインしてコメントする。

その他の回答 (1 件)

Jason Nicholson
Jason Nicholson 2013 年 5 月 27 日

0 投票

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 件のコメント

Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 27 日
thank you Jason!
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 27 日
I would like to count the ones in between. How I can I do that? In this example it would be 7 6 4.
Matt Kindig
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
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 28 日
Suppose that I want find the edges of ones and of not ones. Suppose the array is:
a=[1 1 1 1 1 1 12 10 1 1 1 1 1 11 12 1 1 1 2 3]
a(1:6) -->area1 of ones
a(7:8) -->area1 of not ones
a(9:a13) -->area2 of ones
a(14:15)-->area2 of not ones
a(16:19)-->area3 of ones
a(20) -->area3 of not ones
and so on..

サインインしてコメントする。

カテゴリ

ヘルプ センター および File Exchange で Multidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by