2017-05-10 4 views
2
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 

Antwort

1

können Sie num2cell und deal auf folgende Weise verwenden:

% 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{:}); 
0

Nun, die Linie die Sie suchen, ist dies:

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

Sie können mehr über arrayfun lernen hier

0

Wenn Sie Ihre Matrix M in ein Zellenfeld mit den korrekten Abmessungen konvertieren, Sie können die vektorisierte Version des struct Konstruktor verwenden:

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 

EDIT: ersetzt COLS mit ROWS im Aufruf von mat2cell. Ich verwirrte die Dimensionsgrößen in meinen Tests ...

+0

Sind Sie über Ihre Antwort sicher? – anonymous

+0

Nun, ich habe eine Einschränkung vergessen: Dies funktioniert nur für ein numerisches Array. Aber ansonsten, ja, bin ich mir sicher. Welchen Fehler bekommst du? EDIT: Ja, mein Schlechter, Tippfehler im Code werde ich updaten. – souty

+0

Bro, dieser Code erreicht nicht das gleiche. Ich versuchte es. – anonymous

Verwandte Themen