How to keep only a new modification in an array using for loop?
1 回表示 (過去 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
0 件のコメント
採用された回答
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 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!