function [rv1 rv2]= myfunction(fcn, v, s) % fcn is the function passed in %for loop: for i = 1:length(v) rv1(i) = v(i) + i; end k=1; %while loop: while k<5 %formatted printing: fprintf("k = %d\n",k) k++; end fprintf("Third argument is %f\n",s); %if statement ( options: >= <= == ~= if k > 2 fprintf("Inside if statement...\n"); end %applying function to whole array: rv1 = fcn(v); %operation element by element: (.* ./ .+ etc...) rv2 = 2 .^v; %reading a variable interactively: x = input("Enter a number:"); fprintf("2 x input = %f\n",2*x); %opening a file for write: fid = fopen('mydata.dat', 'w'); if fid < 0 fprintf('Could not open file to write'); return; end for i=1:10 fprintf(fid,"%d %d %d\n", i,i^2,i^3); end fclose(fid); %opening a file for read: fid = fopen('mydata.dat','r'); for i=1:3 fscanf(fid,'%d %d %d'); end fclose(fid) %reading a matrix using load B=load('A.mat') X=B(:,1); Y=B(:,2); fitY=zeros(length(Y),1); %calling another function that computes the nth order polynomial fit to data: params=nthpoly(3,'A.mat'); for j=1:length(params) fitY += params(j)* X .^ (j-1); end %plotting in matlab/octave: clf; hold on; plot(X,Y, '.+r'); plot(X,fitY,'-c'); legend('a+bx+cx2+dx3','location','north'); xlabel('x'); ylabel('y'); title('Fit to third order polynomial'); %creating a hard copy in a .ps file: print('plot.ps','-depsc'); end
last update: Wed May 11, 2016