- #1
Meurig
- 6
- 0
Hi all,
I have the following code:
M = zeros(N)
for i = 1:N
for j = 1:N
M(i,j)= log(norm(rs(:,i)-rc(:,j)))+log(norm(ri(:,i)-rc(:,j)));
end
end
Where rs, rc and ri are 2xN arrays.
Is there a way to construct the matrix without the use of the two for loops?
I'm trying to reduce the time cost of my code.
Thanks,
Meurig
UPDATE:
Have rewritten as:
[rsx,rcx] = meshgrid(rs(1,:),rc(1,:)');
[rsy,rcy] = meshgrid(rs(2,:),rc(2,:)');
M1 = (rsx-rcx).^2;
M2 = (rsy-rcy).^2;
[rix,rcx] = meshgrid(ri(1,:),rc(1,:)');
[riy,rcy] = meshgrid(ri(2,:),rc(2,:)');
M3 = (rix-rcx).^2;
M4 = (riy-rcy).^2;
Ms = log((M1+M2).^(1/2));
Mi = log((M3+M4).^(1/2));
M = Ms+Mi;
Reducing the time cost by 99%.
If anyone has a nicer way of writing this I'd be very interested though!
Cheers,
Meurig
I have the following code:
M = zeros(N)
for i = 1:N
for j = 1:N
M(i,j)= log(norm(rs(:,i)-rc(:,j)))+log(norm(ri(:,i)-rc(:,j)));
end
end
Where rs, rc and ri are 2xN arrays.
Is there a way to construct the matrix without the use of the two for loops?
I'm trying to reduce the time cost of my code.
Thanks,
Meurig
UPDATE:
Have rewritten as:
[rsx,rcx] = meshgrid(rs(1,:),rc(1,:)');
[rsy,rcy] = meshgrid(rs(2,:),rc(2,:)');
M1 = (rsx-rcx).^2;
M2 = (rsy-rcy).^2;
[rix,rcx] = meshgrid(ri(1,:),rc(1,:)');
[riy,rcy] = meshgrid(ri(2,:),rc(2,:)');
M3 = (rix-rcx).^2;
M4 = (riy-rcy).^2;
Ms = log((M1+M2).^(1/2));
Mi = log((M3+M4).^(1/2));
M = Ms+Mi;
Reducing the time cost by 99%.
If anyone has a nicer way of writing this I'd be very interested though!
Cheers,
Meurig
Last edited: