使用循环重复相同的语句

时间:2016-02-15 13:33:39

标签: matlab for-loop

这是3次相同的陈述。如何用循环来做到这一点。这里,矩阵G1的尺寸为3×10。所以在每个部分我都采用不同的专栏。

G2 = f_range_m(1:8:length(timeline_ms),:); %%%% measured range
G1 = OrgiRange(1:8:end,:);

M1 = G1(:,1);
dist11 = abs(bsxfun( @minus,G2,M1));
[~,col1] = min(dist11,[],2);
Result_1 = diag(G2(:,col1));


M2 = G1(:, 2);
dist22 = abs(bsxfun(@minus,G2, M2));
[~,col2] = min(dist22,[],2);
Result_2 = diag(G2(:,col2));

M3 = G1(:, 3);
dist33 = abs(bsxfun(@minus,G2, M3));
[~,col3] = min(dist33,[],2);
Result_3 = diag(G2(:,col3));

我正在尝试这种方式。但是没有得到理想的输出。结果维度应为13 * 3.

obj = 3;
for ix = 1:obj
    M = G1(:,ix);
    dist = abs(bsxfun(@minus,G2,M));
    [~,col] = min (dist,[],2);
    Result = diag(G2(:,col));
end

1 个答案:

答案 0 :(得分:1)

使用您更新的代码,您几乎可以解决它。剩下的一切都是写入Result的列而不是在每次迭代中覆盖它。

obj = 3;
Result=nan(size(G1,1),obj);
for ix = 1:obj
    M = G1(:,ix);
    dist = abs(bsxfun(@minus,G2,M));
    [~,col] = min (dist,[],2);
    Result(:,ix) = diag(G2(:,col));
end