Matrix manipulation / if else loops
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I would like to scan through each row of my data matrix (made of 0s and 1s only) and create a new matrix following the rules below:
- If all columns are 0 - assign 0s to new matrix
- If all columns are 1s - assign 1 to column 2 and 0s to column 1 and 3 of new matrix
- If two columns = 1, then:
- scan up to rows above until you reach a 0 in one of the two columns.
- assign a 1 to the column in the new matrix that was on 0 most recently.
- If both were on 0 equally recently, then assign 1 to both columns.
- (Can assume that first row will be 0 0 0)
This is the code I have so far, but I am struggling on the last section (if two columns both = 1)... any help would be most appreciated. Thank you!
matrix = [0 0 0; 1 0 0; 1 1 0; 1 0 0; 1 0 0; 1 1 1; 0 1 1; 0 1 1; 1 1 1; 1 1 0; 1 1 0; 1 0 0; 1 1 0; 1 0 0]; % data matrix
A = zeros(size(matrix)); % new matrix of 0s to ammend, same size as data matrix
for i = 1:length(matrix(:,1)) % iterate through every row in the data matrix
if sum(matrix(i,:))==0; % if all the columns = 0, assign all columns in new matrix to 0
A(i,:)=0;
elseif sum(matrix(i,:))==3; % if all the columns = 1, assign atrium column in new matrix to 1 and the others to 0
A(i,2)=1;
elseif sum(matrix(i,:))==1; % if only 1 column = 1, assign this column in new matrix to 1 and the others to 0
idx = find(matrix(i,:)); % (find which column it is that =1)
A(i,idx) = 1; % (assign corresponding column in new matrix to 1)
else sum(matrix(i,:))==2; % if two columns =1
idx = find(matrix(i,:)); % find the index of the nonzero elements in this row
idx_1 = (matrix(i-1,idx(1))); % find the values of the row above elements in these columns
idx_2 = (matrix(i-1,idx(2)));
if idx_1 ==0 % if the element in the row above = 0, then assign a 1 to the corresponding column in row i
A(i,idx(1))=1;
if idx_2 ==0 % if the element in the row above = 0, then assign a 1 to the corresponding column in row i
A(i,idx(2))=1;
end
end
end
end
0 个评论
采纳的回答
David Hill
2023-1-19
编辑:David Hill
2023-1-20
Misunderstood you previously.
m = [0 0 0; 1 0 0; 1 1 0; 1 0 0; 1 0 0; 1 1 1; 0 1 1; 0 1 1; 1 1 1; 1 1 0; 1 1 0; 1 0 0; 1 1 0; 1 0 0];
s=sum(m,2);
M=zeros(size(m));
M(s==3,2)=1;
M(s==1,:)=m(s==1,:);
f=find(s==2);
for k=1:length(f)
F=find(m(f(k),:));
t=M(1:f(k)-1,F);
f1=find(~t(:,1),1,'last');
f2=find(~t(:,2),1,'last');
if f2>f1
M(f(k),F(2))=1;
elseif f2==f1
M(f(k),F)=1;
else
M(f(k),F(1))=1;
end
end
M
3 个评论
Voss
2023-1-20
Replace
t=M(1:f(k)-1,F);
f1=find(t(:,1),1,'last');
f2=find(t(:,2),1,'last');
with
t=m(1:f(k)-1,F);
f1=find(t(:,1)==0,1,'last');
f2=find(t(:,2)==0,1,'last');
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!