% mag2geo3.m is used to convert magnetic coords to
% geographical coords. It uses the values given in Appendix 3,
% p534, of Introduction to Space Physics. NOTE that input
% and output are in rads, not degrees. Unlike mag2geo.m and
% mag2geo.m, it allows any size input matrix and returns 
% the same size output.
%%
%% Author: Phillip A. Webb
%% Last updated: June 9 2004                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
%%

function [longo,latgo]=mag2geo3(lonmg,latmg)

[yi,xi]=size(lonmg);                                      %size of input matrices      
lonmg=lonmg(:);                                           %convert lonmg to column vector
latmg=latmg(:);                                           %convert latmg to column vector

radmg=ones(size(lonmg));                                  %unit radi vector
[xv,yv,zv]=sph2cart(lonmg,latmg,radmg);                   %convert from spherical to cartesian coords
tm1=[0.32110 -0.92756 -0.19112];
tm2=[0.94498 0.32713 0];
tm3=[0.06252 -0.18060 0.98157];
tm=[tm1;tm2;tm3];                                         %transformation matrix
res=tm'*[xv';yv';zv'];                                    %transformed result matrix
[longo,latgo,radgo]=cart2sph(res(1,:),res(2,:),res(3,:)); %convert from cartesian to spherical

longo=reshape(longo,yi,xi);                               %required longitude values
latgo=reshape(latgo,yi,xi);                               %required latitude values

