从mathematica到matlab的转换 - > (appendto)

时间:2011-01-25 15:54:22

标签: matlab wolfram-mathematica bsxfun

我在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

1 个答案:

答案 0 :(得分:2)

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

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

如果我理解正确,您需要从正态分布的越来越多的样本中计算平均值和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