Adding a new column to a matrix under certain constraints.

1 回表示 (過去 30 日間)
Jonatan Juslin
Jonatan Juslin 2022 年 8 月 19 日
コメント済み: Jonatan Juslin 2022 年 8 月 19 日
Hi!
I'm having trouble coming up with how to get what I want. I think a picture will best explain what I'm trying to do.
I want to add a new column to my matrix the following way. It starts counting from 1 and changes everytime the two columns are no longer the same.
So for example for the first three rows both columns are the same, at row 4 they change so the counter changes to 2, at row 5 they change again so once again the counter changes to 3 etc.
Any help is greatly appreciated!

採用された回答

Abderrahim. B
Abderrahim. B 2022 年 8 月 19 日
Hi!
This a way to do this logic you described in the question, maybe there better ways !
clear
% Dummy data
wp = [[ones(7,1); 2*ones(2,1); ones(8,1)] , randi(3, 17,1) ] ;
% Preallocation and setting first element of the 3rd column to 1
wpDiff = diff(wp) ;
wpNewCol = zeros(length(wp), 1) ;
wpNewCol(1) = 1 ;
% Algorithm
for ii = 2:length(wpNewCol)
if ~ any(wpDiff(ii-1, :))
wpNewCol(ii ) = wpNewCol(ii - 1) ;
else
wpNewCol(ii) = wpNewCol(ii -1) + 1;
end
end
% New wp
new_wp = [wp, wpNewCol]
new_wp = 17×3
1 3 1 1 2 2 1 2 2 1 2 2 1 2 2 1 3 3 1 3 3 2 1 4 2 2 5 1 2 6
Hope this helps
  1 件のコメント
Jonatan Juslin
Jonatan Juslin 2022 年 8 月 19 日
This is exactly what I wanted, thank you!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by