简体   繁体   English

如何从Matlab中的函数输出制作图形

[英]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. 使用MATLAB函数让我完全不知所措,所以是这种情况:假设我的SUM = 0,并且我有一个恒定的概率P,用户给了我,我必须将此常量P与其他M进行比较(用户也提供M)随机概率,如果P较大,我将SUM加1,如果P较小,我将-1加SUM ...,最后我要在屏幕上打印过程图。

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) (就像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 问题是我的概率P为1,概率为(1-P)为-1,并且SUM相同

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 . 此处的重要函数是cumsum ,它对2*(random>=p)-1生成的+ 1 / -1值的序列求和。

Example graph with p=0.5 , M=2000 : p=0.5M=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 : 对于m = 1000 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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