1

我在mathematica中有以下内容并想在matlab中使用它。我试过但我有错误并且无法修复它们。这是我还没有得到matlab哲学!所以,

intMC = {}; sigmat = {};
Do[np1 = np + i*100;
  xpoints = Table[RandomReal[], {z1, 1, np1}];
  a1t = Table[f[xpoints[[i2]]], {i2, 1, np1}];
  a12 = StandardDeviation[a1t]/Sqrt[Length[a1t]];
  AppendTo[intMC, {np1, Mean[a1t], a12}];
  AppendTo[sigmat, {np1, a12}],
  {i, 1, ntr}];

我这样做了:

  fx=@ (x) exp(-x.^2);

    intmc=zeros();
    sigmat=zeros();

    for i=1:ntr
        np1=np+i*100;
        xpoints=randn(1,np1);
        for k=1:np1
        a1t=fx(xpoints(k))
        end                   %--> until here it prints the results,but in the 
                              %end it gives 
                              % me a message " Attempted to access xpoints(2,:);
                              %index out of bounds because size(xpoints)=[1,200]
                              %and stops executing.

    %a1t=fx(xpoints(k,:))    %  -->I tried this instead of the above but
    %a1t=bsxfun(@plus,k,1:ntr)   % it doesn't work

        a12=std(a1t)/sqrt(length(a1t))
        intmc=intmc([np1 mean(a1t) a12],:) %--> i can't handle these 3 and
        sigmat=sigmat([np1 a12 ],:)        %as i said it stopped executing

    end
4

1 回答 1

2

为了将标量附加到 Matlab 数组,您可以调用array(end+1) = valuearray = [array;value](如果您想要一个 1×n 数组,请用逗号替换分号)。后者也适用于附加数组;要将数组附加到前者,您会调用array(end+1:end:size(newArray,1),:) = newArray以防您想沿第一个维度连接。

然而,在执行超过 100 次迭代的循环中追加,在 Matlab 中是一个坏主意,因为它很慢。您最好先预先分配数组 - 或者甚至更好地对计算进行矢量化,这样您就不必循环了。

如果我理解正确,您想从越来越多的正态分布样本中计算平均值和 SEM。这是使用循环执行此操作的方法:

intmc = zeros(ntr,3); %# stores, on each row, np1, mean, SEM
sigmat = zeros(ntr,2); %# stores, on each row, np1 and SEM

for i=1:ntr
%# draw np+100*i normally distributed random values
np1 = np+i*100;
xpoints = randn(np1,1);
%# if you want to use uniform random values (as in randomreal), use rand
%# Also, you can apply f(x) directly on the array xpoints

%# caculate mean, sem
m = mean(xpoints);
sem = std(xpoints)/sqrt(np1);

%# store
intmc(i,:) = [np1, m, sem];
sigmat(i,:) = [np1,sem];

end %# loop over i
于 2011-01-25T16:18:10.460 回答