mardi 22 août 2017

How to integrate conditions in a MATLAB anonymous function?

My below code is quite time consuming because of a quite big A matrix (150,000^2). Can I integrate the conditions as a function @(x) in accumarray? So that I can work on the cell-based for all the rows b without having to convert into double and apply the condition? I think it will be much faster ! Thank you very much !

tic
[a b c]=find(A.'); %b: rows index
add_sym=accumarray(b,c,[],@(x){x}); % seperate rows into cells
add_r = [];
for i = 1:size(add_sym)
    r = vertcat(add_sym{i})';    
    if size(r,2)==1  % only 2
        add_r0 = 0;
    elseif size(r,2) > 1 && any(r<2)== 0 % many 2s
        add_r0 = r;
        add_r0(1)   = -2;
        add_r0(end) = 2;
        add_r0(2:end-1) = 0;
    elseif size(r,2) > 1 && any(r<2)~= 0 % 2 and 1
        k = find(diff(r)==-1); % find right 2 position
        add_r0 = r;
        add_r0(1)   = -1;
        add_r0(end) = -1;
        add_r0(k) = 2;
        add_r0(2:k-1) = 0;
        add_r0(k+1:end-1) = 0;
    end    
    add_r = [add_r; add_r0'];
end   
ADD = sparse(b,a,add_r,nm,nm,nzmax);

toc

Aucun commentaire:

Enregistrer un commentaire