MATLAB Answers

How to find and replace stand alone values in a logical array

6 ビュー (過去 30 日間)
Teddy Fisher
Teddy Fisher 2019 年 12 月 19 日
コメント済み: the cyclist 2019 年 12 月 19 日
Hello,
I have a logical aray, a 370x29 matrix. I am trying to find all 1s and 0s that are non-consecuitve and replace them with the other one, in each column. So in a series: 00000100000 I want to be able to find and replace that stand alone 1 with a 0, and in a series: 1111101111 I want to find and replace that 0 with a 1. So far, I have been able to find and replace these with this script, where a is my 370x29 matrix:
x=find(a(diff(a)==1),1,1);
y=find(a(diff(a)==-1),1,1);
a(x)=0;
a(y)=1
The only problem with this is that it also finds and replaces the first 1 in a string of 1s and the first 0 in a string of 0s.
Is there any way to find and replace these stand alone 1s and 0s?
Thanks :)

  0 件のコメント

サインイン to comment.

回答 (1 件)

the cyclist
the cyclist 2019 年 12 月 19 日
I think this does what you want:
a(strfind([1 a 1],[1 0 1])) = 1;
a(strfind([0 a 0],[0 1 0])) = 0;

  2 件のコメント

Teddy Fisher
Teddy Fisher 2019 年 12 月 19 日
this hasn't worked. when I try as you have written, i get an error message:
"error using horzcat
dimensions of matrices being concatenated are not consistent."
which i assume is because my input is a matrix. however, when i try to fix this with:
x(strfind([1 1:numel(x) 1],[1 0 1]))=1
OR
x(strfind(1:numel(x),[1 0 1]))=1
nothing happens
the cyclist
the cyclist 2019 年 12 月 19 日
Sorry I was not clear. My code is applied to each row. You'd need to use a loop.
I also see now that you wanted to apply to each column, not row, which makes my code slightly awkward because strfind doesn't handle column data well. However, the following should work:
% Make up an input matrix
v = [0 1 1 0 1 1 1 0 1 1 0]';
a = [v 1-v v];
for nc = 1:size(a,2)
a(strfind([1 a(:,nc)' 1],[1 0 1]),nc) = 1;
a(strfind([0 a(:,nc)' 0],[0 1 0]),nc) = 0;
end
Use your input matrix a, instead of the data I made up.

サインイン to comment.

サインイン してこの質問に回答します。

製品


リリース

R2017b

Translated by