Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
accelerating function

Subject: accelerating function

From: wahyoe Unggul

Date: 18 Jun, 2010 16:58:04

Message: 1 of 2

I have a problem with the function below, if you call the large matrix requires a long time, so that the process of execution to be slow, can you help me modify the function to be able to execute quickly

function [A]=assembly

load scratch_file.txt;
tA=scratch_file;clear scratch_file;
m=max(tA(:,2));
A=zeros(m,m);
%B=zeros(size(tA));
B=A;C=A;
for i=1:length(tA);
    C=A;
   B(tA(i,2),tA(i,3))=tA(i,1);
  A(tA(i,2),tA(i,3))=B(tA(i,2),tA(i,3))+C(tA(i,2),tA(i,3));
end;

Subject: accelerating function

From: Walter Roberson

Date: 18 Jun, 2010 17:41:11

Message: 2 of 2

wahyoe Unggul wrote:
> I have a problem with the function below, if you call the large matrix
> requires a long time, so that the process of execution to be slow, can
> you help me modify the function to be able to execute quickly
>
> function [A]=assembly
>
> load scratch_file.txt;
> tA=scratch_file;clear scratch_file;
> m=max(tA(:,2));
> A=zeros(m,m);
> %B=zeros(size(tA));
> B=A;C=A;
> for i=1:length(tA);
> C=A;
> B(tA(i,2),tA(i,3))=tA(i,1);
> A(tA(i,2),tA(i,3))=B(tA(i,2),tA(i,3))+C(tA(i,2),tA(i,3));
> end;

Is it correct that you do not care what the values of B and C are after the
loop? If so then your loop becomes

for i = 1:length(tA)
   A(tA(i,2),tA(i,3)) = tA(i,1) + A(tA(i,2),tA(i,3));
end

Which can be optimized to a plain vector calculation as

T = sub2ind(size(A),tA(i,2),tA(i,3));
A(T) = A(T) + tA(:,1);


If, though, the tA(i,2),tA(i,3) pairs might be duplicated, then

T = sub2ind(size(A),tA(i,2),tA(i,3));
T1 = accumarray(T,tA(:,1));
T2 = unique(T);
A(T2) = A(T2) + T1(T2);

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us