2017-05-10 75 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 

回答

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{:}); 
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這裏

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 

編輯:在通話與ROWS更換COLSmat2cell。我在測試中混淆了尺寸大小...

+0

你確定你的答案? – anonymous

+0

嗯,我忘了一個警告:這隻適用於數值數組。但是否則,是的,我確定。你會得到什麼錯誤?編輯:是的,我的壞,在代碼中的錯字,我會更新它。 – souty

+0

兄弟,這段代碼沒有達到相同的效果。我嘗試過這個。 – anonymous