フィルターのクリア

How to store " first_element " values?

1 回表示 (過去 30 日間)
parag gupta
parag gupta 2020 年 2 月 21 日
コメント済み: madhan ravi 2020 年 2 月 21 日
Could you please tell how to store the "first_element" values in a matrix?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%code
first_element = [];
end_element = [];
A = [ 1 1 1 1 2 3 4 4 4 ; 1 2 3 4 5 5 5 5 5];
for this_row = A.'
V = this_row';
X = diff(V)~=0;
B = find([true,X]);
E = find([X,true]);
D = 1+E-B ;
first_element = D(1,1)
end_element = D(end);
end
%%%%%%%%%%%%%%%%%%%%
output of the following code is :
first_element =
4
first_element =
1
But I want output to be :
first_element = [ 4 ; 1]
%%%%%%%%%%%%%%%%%%%%%%%%%
Thanks

採用された回答

madhan ravi
madhan ravi 2020 年 2 月 21 日
A = [ 1 1 1 1 2 3 4 4 4 ; 1 2 3 4 5 5 5 5 5];
[first_element,end_element] = deal(zeros(size(A,1),1)); % preallocate
for k = 1:size(A,1)
V = A(k,:);
X = diff(V)~=0;
B = find([true,X]);
E = find([X,true]);
D = 1+E-B ;
first_element(k) = D(1,1);
end_element(k) = D(end);
end
  3 件のコメント
parag gupta
parag gupta 2020 年 2 月 21 日
Thanks Madhan :)
madhan ravi
madhan ravi 2020 年 2 月 21 日
Thank you Stephen :) , you're solution of accumarray() indeed is impressive as always! It's been a while now since I am indulged with MATLAB so couldn't get my head around that function.

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

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 2 月 21 日
編集済み: Stephen23 2020 年 2 月 21 日
No loop needed, here using accumarray:
>> A = [1,1,1,1,2,3,4,4,4;1,2,3,4,5,5,5,5,5]
A =
1 1 1 1 2 3 4 4 4
1 2 3 4 5 5 5 5 5
>> D = diff(A(:,[1,1:end,end]),1,2)~=0;
>> D(:,[1,end]) = true;
>> [C,R] = find(D.');
>> first = accumarray(R,C,[],@(v)v(2)-v(1))
first =
4
1
>> last = accumarray(R,C,[],@(v)v(end)-v(end-1))
last =
3
5
  1 件のコメント
parag gupta
parag gupta 2020 年 2 月 21 日
Thanks Stephen :)

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by