Flipping the numbers 1 to -1

조회 수: 2 (최근 30일)
Offroad Jeep
Offroad Jeep 2016년 2월 11일
댓글: Offroad Jeep 2016년 5월 17일
Hi, to all the members. Consider a matrix 'a' now we take a random number, if random number is >= to 0.5 change the first element from 1 to -1 then calculate mag,if not keep it as 1...... then for next step if random number is < 0.5 keep the matrix and calculate mag, now again take random number and check if now the random number is >=0.5 flip the second element calculate mag.......etc keep on going till the 25th element.
for example
a = 1 1 1 1 random = 0.2324 first element remains same mag = 4
now again take random number random = 0.5649 now a becomes a = -1 1 1 1 mag = 2 now again take random random = 0.6978 a = -1 -1 1 1 mag = 0
random = 0.2345 a = -1 -1 1 1 mag = 0
random = 0.7995 a = -1 -1 -1 1 mag = -1
random = 0.3453 a = -1 -1 -1 1 mag = -1
random = 0.9874 a = -1 -1 -1 -1 mag = -4
end the loop
show mag values and plot against B mag = 4 2 0 0 -1 -1 -4
B =linspace(2,0,numel(mag)) plot(B,mag)
thanks for guidance
  댓글 수: 7
Offroad Jeep
Offroad Jeep 2016년 2월 11일
I will be grateful if you can help me in this regard.......... and i think i will be able to solve the problem where i want to fit this logic.......
Offroad Jeep
Offroad Jeep 2016년 5월 17일

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

채택된 답변

Stephen23
Stephen23 2016년 2월 11일
편집: Stephen23 2016년 2월 12일
Try using a while loop:
a = ones(1,4)
k=1;
mag=[];
while k<=numel(a)
x = rand()>=0.5;
a(k)=a(k)-2*x;
mag(end+1)=sum(a);
k=k+x;
end
Produces:
a =
-1 -1 -1 -1
mag =
4 4 2 2 2 0 -2 -4
  댓글 수: 7
Stephen23
Stephen23 2016년 2월 12일
If my answer resolves your question then please accept it.
Offroad Jeep
Offroad Jeep 2016년 5월 17일

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2016년 2월 11일
help numel
help for
help rand
help if
help sum
% for k=1:N
% if ...
% A(k) = -A(k)
% B(k) = sum ...
% end

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by