Reputation: 123
When I run this example codes, I found it take more time on the 8 line. I don't why, and is there any tips let it faster??
The x and y value is not important, I just curious about the red line why take so much time, in the real codes, they are two complex expressions, why storage take so much time?
result = zeros(2, 1000);
x=0;y=0;
tic
for i =1:200
for j =1:200
for k =1:1000
x=x+x/2+2*y; y=y+x*y/2;
result(:, k) = [x;y];
end
sum(result); % or other operations, just for example
end
end
toc
Upvotes: 0
Views: 68
Reputation: 1979
Explicit looping is generally going to be slow compared to vector operations. In this case you can do:
x=0;y=0;
tic
for i =1:200
for j =1:200
result=[x+(1:1000)*i; y+(1:1000)*j];
x=x+1000*i;
y=y+1000*j;
sum(result); % or other operations, just for example
end
end
toc
Edit: In your revised example, do explicit updating instead of vector construction and slice assignment:
result = zeros(2, 1000);
x=0;y=0;
tic
for i =1:200
for j =1:200
for k =1:1000
x=x+x/2+2*y; y=y+x*y/2;
result(1, k) = x;
result(2, k) = y;
end
sum(result); % or other operations, just for example
end
end
toc
Upvotes: 2