%Beginners Introduction to MATLAB WORKSHOP %Given by Michael Cohen University of Connecticut, Agricultural and %Resource Economics, Food Marketing Policy Center. Novermber 2, 2007 %The m-file clear all %make comment on suppressing output x=1+1; y=2*2^2; z=sin(y); w=log(x) %sqrt exp %vectors v=[1 4 log(y)]; vprime=v'; q=v(1); t=[q;v']; tsq=t.^2; %string vector a=['mike']; b=['went']; c=['fishing']; sentance=[a ' ' b ' ' c]'; disp(sentance) %plotting functions %make grid on which to evaluate N=10; h=1/N; x=0:h:N; f=cos(x); plot(x,f,'k:') title('cos(x)') ylabel('f(x)') xlabel('x') %text(3,.8,'f=cos(x)') %%matricies %%goto excel and create a data file M=dlmread('mydata1.txt','\t',1,0); save M P=M*M; [r c]=size(P); Q=P(:,1:2); Z=[P(:,1) P(:,3)]; A=Q*Z'; H=A.*ones(3,3); B=A.*eye(3); steve=diag(B); C=A.*zeros(3,3); W=[H B C ones(3,3)]; i=ones(2,1); j=eye(3); K=kron(i,j); Y=reshape(K,2,9); U=repmat(j,2,3); S=inv(randn(3,3)); %make a quick comment on generalized inverse %User defined functions fac3=fac(3); disp(['Three Factorial' ' ' num2str(fac3)]) %Example of how clever use of matlab functions can dramatically speed up %computation time. tic n=100; v=ones(n,1); it=1; ij=sqrt(n); for i=1:sqrt(n) x(i)=sum(v(it:ij)); it=ij+1; ij=(i+1)*sqrt(n); end toc tic n=100; t=sqrt(n); x1=reshape(v,t,t); x2=sum(x1,1); toc %an example useing the while function %Newton-Raphson algorithum for finding zeros (roots) of a function syms x %command sysms ques symbolic package and x denotes the symbol/var f=x^2+5*x; j=jacobian(f,x); h=jacobian(j,x); epsilon=.00001; x0=1; %initial guess dif=1; while abs(dif)>epsilon x=x0; je=eval(h); %evaluates the jacobian at the guess fe=eval(j); %evaluate FOC at guess x1=x0-inv(je)*fe; dif=x1-x0; %distance from guess and new value x0=x1; %update guess it=it+1; end disp(x1)