for loop to scan matrix and output a new matrix

1 回表示 (過去 30 日間)
Laura Steel
Laura Steel 2022 年 8 月 19 日
コメント済み: Laura Steel 2022 年 8 月 19 日
I would like to take an e.g. 8x1 matrix such as the one below:
0
1
0
1
1
1
0
1
and I would like to scan through it and generate a new matrix of the same dimensions, following the rules below.
  • Make the first value of the new matrix the same as the first value of the original matrix.
  • Then from here on:
  • If the value is 0, add a 0 to the new matrix.
  • If the value is 1 AND the value above it is 1, assign a 0 to the new matrix.
  • However, if the value is 1 but the value above it is 0, then assign a 1 to the new matrix.
So, the resulting matrix should be:
0
1
0
1
0
0
0
1
Any help, with clear notation of what each part of the for loop is doing, would be much appreciated! Many thanks.
  2 件のコメント
Rik
Rik 2022 年 8 月 19 日
Why don't you write the first version?
Laura Steel
Laura Steel 2022 年 8 月 19 日
編集済み: Walter Roberson 2022 年 8 月 19 日
I think I may have worked something out! But I am not sure it is the best/simplest way of doing it?
matrix = [0; 1; 0; 0; 1; 1; 1; 1; 0; 0; 1; 1; 0];
matrix_new = zeros(13,1);
for i = 1:length(matrix)
if i == 1
matrix_new(i,1) = matrix(1,1);
end
if matrix(i,1) == 0
matrix_new(i,1) = 0;
end
if matrix(i,1) == 1 & matrix(i-1,1) ==0
matrix_new(i,1) = 1
end
if matrix(i,1) == 1 & matrix(i-1,1) ==1
matrix_new(i,1) = 0
end
end

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

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 8 月 19 日
matrix = [0; 1; 0; 0; 1; 1; 1; 1; 0; 0; 1; 1; 0];
matrix_new = [matrix(1); matrix(2:end) & ~matrix(1:end-1)]
matrix_new = 13×1
0 1 0 0 1 0 0 0 0 0
  5 件のコメント
Walter Roberson
Walter Roberson 2022 年 8 月 19 日
inf and -inf are not a problem, but nan is a problem.
~[-inf inf]
ans = 1×2 logical array
0 0
~nan
Error using ~
NaN values cannot be converted to logicals.
Laura Steel
Laura Steel 2022 年 8 月 19 日
Brilliant, thank you both very much.

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

カテゴリ

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