简体   繁体   中英

How to make a graph from function output in matlab

I'm completely lost at this using MATLAB functions, so here is the case: lets assume I have SUM=0, and I have a constant probability P that the user gives me, and I have to compare this constant P, with other M (also user gives M) random probabilities, if P is larger I add 1 to SUM, if P is smaller I add -1 to SUM... and at the end I want print on the screen the graph of the process.

I managed till now to make only one stage with this code:

function [result] = ex1(p)
if (rand>=p) result=1;
else result=-1;
end

(its like M=1)

How do You suggest I can modify this code in order to make it work the way I described it before (including getting a graph) ?

Or maybe I'm getting the logic wrong? the question says I get 1 with probability P, and -1 with probability (1-P), and the SUM is the same

Many thanks

You can do it like this:

p = 0.25; % example data
M = 20; % example data

random = rand(M,1); % generate values
y = cumsum(2*(random>=p)-1); % compute cumulative sum of +1/-1
plot(y) % do the plot

The important function here is cumsum , which does the cumulative sum on the sequence of +1/-1 values generated by 2*(random>=p)-1 .

Example graph with p=0.5 , M=2000 :

在此处输入图片说明

I'm not sure how you achieve your input, but this should get you on the way:

p = 0.5;            % Constant probability
m = 10;
randoms = rand(m,1) % Random probabilities

results = ones(m,1);
idx = find(randoms < p)

results(idx) = -1;

plot(cumsum(results))

For m = 1000 : 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM