将数据从for循环存储到MATLAB中

时间:2013-01-22 12:47:45

标签: matlab

我有一个计算方差的循环,我想绘制。

for k = [1:3]
disp(B.colheaders{1, k});
%disp(B.data(1:79, k + 1));
for j = [1:10:79]
    disp(j)
    Variance = var(B.data(j:j+8, k))
end
%disp(V)
plot(Variance)
end

如何将差异存储到数组或矩阵中,以便我可以将它们全部绘制出来?

1 个答案:

答案 0 :(得分:3)

如果你想保持循环,这是一种方法:

figure,hold on %# avoid erasing the previous plots
for k = [1:3]
disp(B.colheaders{1, k});
%disp(B.data(1:79, k + 1));
startIdx = [1:10:79];
Variance = zeros(size(startIdx));
for j = startIdx
    disp(j)
    Variance(j==startIdx) = var(B.data(j:j+8, k))
end
%disp(V)
plot(Variance)
end

这是一种跳过内循环的方法

figure,hold on
for k = [1:3]
disp(B.colheaders{1, k});
%disp(B.data(1:79, k + 1));
startIdx = [1:10:79];
varIdx = bsxfun(@plus,startIdx,(0:7)'); %# create array for indexing

currentData = B.data(:,k);

%# calculate variance for each column
Variance = var(currentData(varIdx),1,1);

plot(Variance)
end