How to keep only a new modification in an array using for loop?

2 views (last 30 days)
Hello, I have an array named 'a' cocsists of ones and zeros. What I want is
If an entry is zero , make it 1 and store the whole array, then move to the next term and if the elemnt is 1 store the array as it is and move to the next element in the array. I have tried in the code below but gives me a different answer. If anyone can help me in this.
a=[1 0 0 1 1 0 0 1 0];
i=1;
new=[];
for j=1:9
if a(i)==0
a(i)=1;
new(i,:)= a;
else
new(i,:)=a;
end
i=i+1
end
output of the above code
1 0 0 1 1 0 0 1 0
1 1 0 1 1 0 0 1 0
1 1 1 1 1 0 0 1 0
1 1 1 1 1 0 0 1 0
1 1 1 1 1 0 0 1 0
1 1 1 1 1 1 0 1 0
1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 0
1 1 1 1 1 1 1 1 1
What I want is
desired output=[1 0 0 1 1 0 0 1 0
1 1 0 1 1 0 0 1 0
1 0 1 1 1 0 0 1 0
1 0 0 1 1 0 0 1 0
1 0 0 1 1 0 0 1 0
1 1 1 1 1 1 0 1 0
1 0 0 1 1 0 1 1 0
1 0 0 1 1 0 0 1 0
1 0 0 1 1 0 0 1 1

Accepted Answer

Jan
Jan on 5 Dec 2022
Edited: Jan on 5 Dec 2022
a = [1 0 0 1 1 0 0 1 0];
new = repmat(a, numel(a), 1);
for j = 1:numel(a)
if new(j, j) == 0
new(j, j) = 1;
end
end
Alternatively:
a = [1 0 0 1 1 0 0 1 0];
na = numel(a);
new = zeros(na, na);
for j = 1:na
new(j, :) = a;
new(j, j) = 1;
end
The variables i and j have the same value in your code, so you can omit this redundant information.
Instead of modifying the original vector a, only the value in the output is changed in my code.
A simpler method to get the same output:
a = [1 0 0 1 1 0 0 1 0];
new = a | eye(numel(a));

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!