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

조회 수: 3 (최근 30일)
lilly lord
lilly lord 2022년 12월 5일
댓글: lilly lord 2022년 12월 5일
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