Probability and If commands.

  • MATLAB
  • Thread starter Beer-monster
  • Start date
  • #1
296
0

Main Question or Discussion Point

Hi

I'm working on my first matlab script that I've worked on from scratch. I've never taken a course in matlab, the only experience I've had is to modify a couple of other scripts. I'm hoping to develop my matkab skills with a 'relatively' simple monte carlo model: a 2D Ising model.

One part of my method is to take a binary array of zeros and ones, pick a 'random' element and switch the value from zero to one or vice versa. I've done this with a simple if/else command.

if I==1
I=0;
else I=1;
end


What I'd like to do is introduce a probability, so that the value flip will occur with a certain probability p. Is there anyway to add this into my if command or do I need tp try something more sophisticated?
 

Answers and Replies

  • #2
34,043
9,891
You can generate a random number between 0 and 1 or between 0 and N (whatever Matlab can do easily) and then check if this random number is smaller than your target probability (or N times that probability). Flip if yes.
Code:
if rand<p
  I=1-I;
end
 

Related Threads on Probability and If commands.

Replies
4
Views
13K
Replies
4
Views
742
  • Last Post
Replies
1
Views
612
Replies
2
Views
2K
Replies
2
Views
5K
Replies
2
Views
2K
  • Last Post
Replies
5
Views
3K
  • Last Post
Replies
11
Views
1K
  • Last Post
Replies
1
Views
512
Top