How do I resolve these two lines separately?

조회 수: 2 (최근 30일)
Sandi Homolak
Sandi Homolak 2022년 4월 21일
댓글: Jon 2022년 4월 21일
So I have matrix A that is 3x5 and a matrix B with random values and same dimensions as matrix A.
I want to find the elements in matrix B where the generated random number is lower than 0.6 and then change the coresponding elements in matrix A from 0 to 1 or from 1 to 0. Is there a way to do this without going into a for loop?
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
A(B<0.6 & A==0)=1
A(B<0.6 & A==1)=0
When I run this code it does what it's supposed to but the last line takes the newly-formed ones and then turnes them into zeros as well (which is not what i want).
  댓글 수: 2
Jon
Jon 2022년 4월 21일
Can you please clarify what you are trying to do. What is the role of the original values of A in this. Maybe give a small example.
Sandi Homolak
Sandi Homolak 2022년 4월 21일
it is an example of mutation in a genetic algorithm where every element has 60% chance to mutate

댓글을 달려면 로그인하십시오.

채택된 답변

Sandi Homolak
Sandi Homolak 2022년 4월 21일
Solved it.
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
T=find(B<0.6 & A==1)
Z=find(B<0.6 & A==0)
A(T)=0;
A(Z)=1;

추가 답변 (3개)

Les Beckham
Les Beckham 2022년 4월 21일
Another approach
B=rand(3,5)
B = 3×5
0.2205 0.2334 0.8353 0.4513 0.3142 0.6426 0.4411 0.6683 0.8477 0.4905 0.0294 0.5650 0.2777 0.6241 0.4927
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
A = 3×5
0 0 0 1 0 1 1 1 0 0 1 0 1 1 0
idx = B > 0.6
idx = 3×5 logical array
0 0 1 0 0 1 0 1 1 0 0 0 0 1 0
A(idx) = ~A(idx)
A = 3×5
0 0 1 1 0 0 1 0 1 0 1 0 1 0 0

Jon
Jon 2022년 4월 21일
편집: Jon 2022년 4월 21일
It looks like you may have already answered your own question, but I think this is a little cleaner approach to do the same thing
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
Aold = A;
A(B<0.6 & Aold==1) = 0;
A(B<0.6 & Aold==0) = 1;
  댓글 수: 1
Jon
Jon 2022년 4월 21일
Actually you can do it in one line
A = double((B < 0.6 & ~A) | (B > 0.6 & A))
I turn the result into a double otherwise you would have a logical array rather than an array of ones and zeros. Not sure if that matters for your application

댓글을 달려면 로그인하십시오.


Tala
Tala 2022년 4월 21일
편집: Tala 2022년 4월 21일
try this
B=rand(3,5);
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0];
B1=B>0.6;
A(B1)=1;
  댓글 수: 1
Sandi Homolak
Sandi Homolak 2022년 4월 21일
This only changes the zeros in A into ones, but not the ones in A into zeros. I need both to happen.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Genetic Algorithm에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by