是否有可能摆脱以下代码中的循环?

时间:2017-05-10 13:15:47

标签: matlab

function [lines1, max_vertex1] = matrix_to_arg(matrix1)
%   convert a matrix into a vector of line-structs
%   and, one vector.
[ROWS, COLS] = size(matrix1);

if(~(COLS==10))
    fprintf('matrix1 must have 10 columns\n');
    return;
end

max_vertex1 = matrix1(1, 7:10);
M = matrix1(:, 1:6);

    for i=1:ROWS
        lines1(i) = struct( 'point1', M(i,1:2), ... 
                 'point2', M(i,3:4), ... 
                  'theta', M(i,5), ... 
                    'rho', M(i,6));
    end
end

3 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用num2celldeal

% random data
M = rand(5000, 6);
% split each row to cell
point1 = num2cell(M(:,1:2),2);
point2 = num2cell(M(:,3:4),2);
theta = num2cell(M(:,5),2);
rho = num2cell(M(:,6),2);
% init struct
lines1 = struct('point1',[],'point2',[],'theta',[],'rho',[]);
lines1(size(M,1)).point1 = [];
% deal data to struct
[lines1(:).point1] = deal(point1{:});
[lines1(:).point2] = deal(point2{:});
[lines1(:).theta] = deal(theta{:});
[lines1(:).rho] = deal(rho{:});

答案 1 :(得分:0)

你正在寻找的是这条线:

lines1 = arrayfun(@(i) struct( 'point1', M(i,1:2), 'point2', M(i,3:4), 'theta', M(i,5), 'rho', M(i,6)), 1:ROWS);

您可以在此处详细了解arrayfun

答案 2 :(得分:0)

如果将矩阵M转换为正确维度的单元格数组,则可以使用struct构造函数的矢量化版本:

function [lines1, max_vertex1] = matrix_to_arg(matrix1)
%   convert a matrix into a vector of line-structs
%   and, one vector.
[ROWS, COLS] = size(matrix1);

if(~(COLS==10))
    fprintf('matrix1 must have 10 columns\n');
    return;
end

max_vertex1 = matrix1(1, 7:10);
M           = mat2cell(matrix1(:, 1:6),ones(1,ROWS),[2 2 1 1]);

lines1      = struct('point1', M(:,1), ... 
                     'point2', M(:,2), ... 
                     'theta',  M(:,3), ... 
                     'rho',    M(:,4));
end

编辑:在COLS的调用中将ROWS替换为mat2cell。我在测试中混淆了尺寸大小......