How do I replace cell in specific column
Show older comments
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 Comments
Rik
on 23 Jan 2019
I can say I really understand what you mean. How do you determine which zeros should be changed to a one? Should the solution assume you know which column should be left alone, or should that be determined?
Something that might be a nice step towards a solution: if you need to fill the zeros from the top, you can actually use find. If you transpose your matrix, you can use find to find the first k linear indices.
S A
on 23 Jan 2019
Guillaume
on 23 Jan 2019
and no somthing I have to tell you about
Let us be the judge of that. Your example is so trivial, that
M = [0 1 0 1
1 1 1 0
1 0 1 1
0 1 0 1] %your demo input
M(:, [2 4]) = 1
would get your desired output. So give us as much details as possible so we can give you an answer that actually do what you want.
S A
on 23 Jan 2019
Image Analyst
on 24 Jan 2019
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???
Accepted Answer
More Answers (1)
Image Analyst
on 23 Jan 2019
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"?
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!