How do I replace cell in specific column
21 ビュー (過去 30 日間)
古いコメントを表示
Hi, I have matrix n*n, let's say 4*4
0 1 0 1
1 1 1 0
1 0 1 1
0 1 0 1
And I want change the values of 0 to 1 (just 3 zeros maximum) from the first and second and fourth column (I can not change from third column)
It will becomes
1 1 0 1
1 1 1 1
1 1 1 1
0 1 0 1
So that's what I should to got, my problem is too complicated so I have if condition if the cell is out of specific part and it is zero, then change it..
if numZeros1 > numZeros2
diff = numZeros1 - numZeros2; %for example = 3
for i=1: diff
if offspring1(:, [1:crossoverPoint1-1 crossoverPoint2:end]) == 0 %to change out of portion which is here the third column
end
end
This what I tried but I can't complete it and I think it is wrong :(
To summary, I want to change specific number of 0 to 1 for specific portion in a matrix, how can I do it please?
5 件のコメント
Image Analyst
2019 年 1 月 24 日
But you're changing more than 3 zeros. You said "(just 3 zeros maximum)" and now you're changing 4 zeros to 1s. Why???
And why did the second zero in the last column change to 1, but not the second zero in the first column???
採用された回答
Guillaume
2019 年 1 月 23 日
Now that you've explained clearly what you want:
A = [0 1 1 0 1 0 0
1 1 1 1 1 1 1
1 1 1 1 0 1 1
1 0 1 1 1 1 1
1 1 1 1 0 1 0
1 1 0 1 1 1 1
0 1 1 1 1 1 1] %demo matrix
crossoverPoint1 = 3
crossoverPoint2 = 6
replacecount = 4;
A = A.'; %swap row columns as you seem to prioritise rows over columns
Adup = A; %to keep original matrix
Adup(crossoverPoint1:crossoverPoint2, :) = 1; %don't care about 0s in these rows (originally columns). Set everything to 1
A(find(Adup == 0, replacecount)) = 1; %replace the first replacecount 0s by 1s.
A = A.' %transpose back
2 件のコメント
Image Analyst
2019 年 1 月 24 日
This changes more than 3 zeros. It changes 4 zeros. In the original question he said "just 3 zeros maximum" however he did seem to break that requirement later in the comments for some reason. It's inconsistent to me.
その他の回答 (1 件)
Image Analyst
2019 年 1 月 23 日
This simple and intuitive for loop will do it.
m = [0 1 0 1
1 1 1 0
1 0 1 1
0 1 0 1]
[rows, columns] = size(m)
changeCount = 0;
% Change the first zero in each column
% except column 3, and quit after
% 3 zeros have been changed.
for col = 1 : columns
if col == 3
continue; % Skip column 3 for some reason.
end
for row = 1 : rows
if m(row, col) == 0
m(row, col) = 1;
changeCount = changeCount + 1;
% Now that we've changed one in this column,
% skip to the next column.
break;
end
end
if changeCount == 3
break;
end
end
m % Show in command window.
By the way, why do you want to do this quirky thing? What's the "use case"?
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!