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

3 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2022-12-5
编辑:Jan 2022-12-5
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));

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by