MATLAB: How to solve the error in the following code ”Index Exceeds matrix dimension”

matrix

nt = 100;
nz = 60;
x=linspace(0,2*pi*50,nt);
y=linspace(-80,20,nz);
[X,Y]=meshgrid(x,y);
for i = 1:nt
for j = 1:nz
G(i,j) = 5-(3*cos(X(i,j)/50)); %#ok<SAGROW>
end
end
[n3,n4]=size(G) %#ok<NOPTS>
Why this code generates the dimension as 120 * 120.
Kindly Help.

Best Answer

You need to reverse the index assignments:
for i = 1:nz
for j = 1:nt
G(i,j) = 5-(3*cos(X(i,j)/50)); %#ok<SAGROW>
end
end
However you can avoid the loops entirely:
G = 5-(3*cos(X/50));
This produces the same result.
‘Why this code generates the dimension as 120 * 120.’
I cannot reproduce that. When I run it, ‘G’ is (60 x 100).