Need help for vectorization?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello
This program is running very slow. Can anyone please help me to make it fast like by vectorizing this code.
Thanks
Note that---Pop_Size,n,dr,f,S,T are my inputs. i am giving f,S,T input as matrix like[f S T]
for u= 1:Pop_Size
ridx = 1;
c=n-1;
output = zeros(n,n*dr);
for z = 1:n:n*dr
M = zeros(c);
f = inputData(ridx,1); % f= Demand
S = inputData(ridx,2); % S= Source node
T = inputData(ridx,3); % T= Termination node
ridx = ridx + 1;
for k = 1:f
p = randperm(c);
for s = 1:c
M(p(s),s) = M(p(s),s) + 1;
end
end
M = [M(:,1:S-1),zeros(c,1),M(:,S:c)]; % Add column of zeros
M = [M(1:T-1,:);zeros(1,c+1);M(T:c,:)];% Add row of zeros
M(1:(c+2):(c+1)*(c+1))= 0;
output(:, z:z+c) = M;
end
outp(:,:,u) = output(:,:); %To save all the chromosomes
fprintf('Chromosome %d\n',u);
disp(output);
end
0 Kommentare
Antworten (2)
Roger Stafford
am 5 Sep. 2014
Bearbeitet: Roger Stafford
am 5 Sep. 2014
In your Aug. 20 Answers #151724 article "Please help me to modify the following program" I showed how you could replace all your current code that creates the M matrix with just three lines of code using the 'accumarray' function. It replaces two nested for-loops. This could possibly improve your execution time. Why don't you try it?
1 Kommentar
Guillaume
am 6 Sep. 2014
If output is significantly large, then, yes, the resizing of outp will slow down your program as matlab has to copy the whole content into a new memory slot each time. You can:
Either, predeclare outp:
outp = zeros(n, n*dr, Pop_Size);
Or store output into a cell array:
outp{u} = output;
Guillaume
am 5 Sep. 2014
I'm not sure there's much that can be vectorised in there. An alternative for your for k loop could be:
coloffset = 0:c:c^2-1;
for k = 1:f
indices = randi(c, 1, c) + coloffset;
M(indices) = M(indices) + 1;
end
But on my machine it's only faster for c>70.
The insertion of a row and column of zero is going to be expensive, so instead I would do:
M = zeros(c+1); %i.e. M = zeros(n);
%randomly add 1 to a row of column 1:n, but never in last row, using whichever method
%with your method change s to go from 1:n (but p still randperm(c))
%with mine change randi to be randi(c, 1, n) and coloffset to be 0:n:n^2-1
M(:, S) = 0; %set column to 0
M(end, :) = M(T, :); %swap row T with last row
M(T, :) = 0;
Finally, you could change setting the diagonal to 0 to:
M(logical(eye(n)) = 0;
Don't know if it's faster.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Fourier Analysis and Filtering finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!