How Can I Introduce Probability into My MATLAB If Command?

  • Context: MATLAB 
  • Thread starter Thread starter Beer-monster
  • Start date Start date
  • Tags Tags
    Probability
Click For Summary
SUMMARY

The discussion focuses on incorporating probability into MATLAB's conditional statements, specifically within a Monte Carlo simulation for a 2D Ising model. The user initially employs a basic if/else structure to toggle a binary value but seeks to introduce a probabilistic element to this process. The solution provided involves generating a random number using MATLAB's rand function and comparing it to a specified probability p to determine whether to flip the binary value. This method effectively enhances the randomness of the value switch in the simulation.

PREREQUISITES
  • Basic understanding of MATLAB programming
  • Familiarity with binary arrays and conditional statements
  • Knowledge of Monte Carlo simulations
  • Understanding of random number generation in MATLAB
NEXT STEPS
  • Explore MATLAB's rand function for random number generation
  • Learn about Monte Carlo methods in statistical modeling
  • Investigate advanced conditional statements in MATLAB
  • Study the implementation of the Ising model in computational physics
USEFUL FOR

Individuals learning MATLAB programming, researchers working on Monte Carlo simulations, and anyone interested in implementing probabilistic models in computational tasks.

Beer-monster
Messages
285
Reaction score
0
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?
 
Physics news on Phys.org
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
 
  • Like
Likes   Reactions: Wrichik Basu

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
11K
  • · Replies 2 ·
Replies
2
Views
11K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 13 ·
Replies
13
Views
4K
  • · Replies 2 ·
Replies
2
Views
10K
  • · Replies 3 ·
Replies
3
Views
5K
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
6K