Shortening run time to compute function

1 view (last 30 days)
Kyle Barber
Kyle Barber on 22 Nov 2020
Commented: Kyle Barber on 22 Nov 2020
Hello, I am pretty new to MATLAB. I have created the following function which I am using to generate any n x n matrix. I need to generate a 256 x 256 matrix that I will then multiply by another 256 x 256 matrix.
When I set n to be equal to 256 to generate said matrix, the code runs on and on.
Is there a rounding or some sort of simplification I can make to the function?
function matrix=function1(n)
matrix=zeros(n);
for i=1:n
for j=1:n
matrix(i,j)=sqrt(2/n)*sin((pi*(i-(1/2))*(j-(1/2)))/n)
end
end
end
I ultimately will apply the above function in this string of code.
Y_int=imread('Cat Photo 2.jpg');%Display photo 2
Y_double=double(Y_int); %Covert to double
Y_gray=0.3*Y_double(:,:,1)+0.3*Y_double(:,:,2)+0.3*Y_double(:,:,3);
colormap('gray');
DST=function1(256);
DSTMatrix=DST*Y_gray;
p=0.2
%when p=0, no data is saved
%when p=1 all data is saved
for i=1:n
for j=1:n
if i+j>p*2*n
DSTMatrix(i,j)=0;
end
end
end
DSTMatrix2=DSTMatrix*DST
imagesc(uint8(DSTMatrix2));
If someone could please help that would be great!
Thanks

Answers (1)

KSSV
KSSV on 22 Nov 2020
Edited: KSSV on 22 Nov 2020
This function:
function matrix=function1(n)
matrix=zeros(n);
for i=1:n
for j=1:n
matrix(i,j)=sqrt(2/n)*sin((pi*(i-(1/2))*(j-(1/2)))/n)
end
end
end
You are printing the output for everytime on the screen. This will eat away your time. That function can be completely replaced with:
function matrix=function1(n)
[i,j] = meshgrid(1:n,1:n) ;
matrix = sqrt(2/n)*sin((pi*(i-(1/2)).*(j-(1/2)))/n) ;
end
The below lines of code:
for i=1:n
for j=1:n
if i+j>p*2*n
DSTMatrix(i,j)=0;
end
end
end
can be repalced with:
[i,j] = meshgrid(1:n,1:n) ;
idx = (i+j) > p*2*n ;
DSTMatrix(idx) = 0 ;
  1 Comment
Kyle Barber
Kyle Barber on 22 Nov 2020
Thanks for the response. I played with the code a little more and was able to get it to work. Mods please close. Thanks!

Sign in to comment.

Tags

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!