Labels

Matlab Helps

1) how to plot a GIS file in Matlab?

>> filename = 'C:\Users\...\file.shp'
>> plot([Shp.X],[Shp.Y], 'k-');

2) Delete a particular line or element in an exiting plot, leaving the rest intact

>> figure(1)
>> p1 = plot(x,y); hold on
>> p2 = plot(C1,C2); % this is what we want to remove
>> delete(p2)

3) Change background color of a plot

>> set(gca,'Color',[0.8 0.8 0.8])

4) Plot variance intervals, or confidence intervals with a filled region. I got this idea from: MrMartin. Thanks!

>> plot_variance = @(x,lower,upper,color) set(fill([x,x(end:-1:1)],[upper,lower(end:-1:1)],color),'EdgeColor',color);
>> plot_variance(X,ME-2*SD,ME+2*SD,[1 1 1]*214/255);hold on
>> plot_variance(X,ME-SD,ME+SD,[1 1 1]*224/255);hold on
>> plot(X,ME,'o-','MarkerFaceColor','w','LineWidth',2)

5) Angles of coordinates expressed from 0 to 360 degrees.

>> Angle = @(x1,y1,x2,y2) 1/((2*pi) * 360) * mod(atan2((y2-y1),(x2-x1)),2*pi);

6) Interpolate scattered (spatial) data. You don't need to create a mesh, etc... much better

>> zq = griddata(x,y,z,xq,yq)

7)  Save a TIFF figure with resolution of 300 dpi from current figure.

>> print -dtiff -r300 picture1
Another option:
>> I = getframe(gcf);
>> imwrite(I.cdata,'figure.tif', 'Resolution', 300)

8)  What's the Matlab equivalent of Excel's VLookup? (Look up table). More info here
Say that codesLU = [1 2 3 4 ; .1 .2 .15 .6], and that LU is [2 2 1 3]  in which: C = [1 2 3 4; .2 .2 .1 .15];

>> [la,idx] = ismember(LU,codeLU(:,1));
>> C = codeLU(idx(la),:)

9)  How to sort and reverse sort a vector? Taken from here.

>> A = [1 8 3 17 0 4 7];
>> [sortA, ind] = sort(A); % Sort A
>> unsorted = 1:length(A); %
>> newInd(ind) = unsorted; % Build a the reverse sorting index
>> newA = sortA(newInd); % reverse sorting.

10) Convert NaNs to 0

>> A(isnan(A)) = 0;

11) Find if point is inside polygon (works for shapefile?)

>> IN = inpolygon(X,Y,XV,YV);

12) Print figure whose axis look as those in screen

>> set(gcf,'PaperPositionMode','auto')

13) Plot smooth lines

>> plot(x,y,'b','LineSmoothing','on')

14) Sample from Gaussian Mixture Model (GMM)

>> options = statset('Display','final');
>> gm = gmdistribution.fit([X Y],2,'Options',options); %2 components
>> Ysamp = random(gm,10000); % Ysampled is 10000x2. random is the key command
>> ezcontour(@(x,y)pdf(gm,[x y]),[-70 -37],[5 20])
>> gm_sam = gmdistribution.fit([Ysamp(:,1) Ysamp(:,2)],2,'Options',options); % To check the 2d Pdf of the synthetically generated points.

15) get limits of a plot

>> Xlims = get(gca,'xlim'); Ylims = get(gca,'ylim');

16) Keep the background of figure the same as is shown on the screen when printed

>> set(gcf,'InvertHardCopy','off');

or conversely from  the figure window:
File/Print Preview/Color tab/Select Same as Figure/Close
More here

17) Set limits of colorbar

>> caxis([cmin cmax])

18) Find best distribution

>> allfitdist(data,'PDF')

19) Create a distribution object

>> pdfig = ProbDistUnivParam('inversegaussian',[mu lambda]);

20) Plot the distribution object

>> plot(pdf(pdfig,1:30))

21) Check if a cell is empty

>> cellfun('isempty',Cell);

22) Calculate length of a trajectory (lat/long) on earth

>> dist = stdist(Lat,Long);

23) Bring layers top or bottom in a figure

>> uistack(gs,'bottom')

24) Identify intersection of lines (polygons)

>> [xi,yi] = polyxpoly(x1,y1,x2,y2);

25) Plot Weibull pdf

>> Y = wblpdf(X,A,B)

26) Create color vector

>> CM = jet(n);

27) Convert cell to vector

>> V = [cell{1,1,1:5}];

28) Find non-empty elements in a cell

>> b = find(cellfun('isempty',cell))

29)      How to assign a different name to variable loaded to the workspace by the command ‘load’ that is inside a ‘struct’ field?

If A is the field and you don’t know the name of the variable inside it do:

>> B = getfield(A,char(fieldnames(A)));

char(fieldnames(A)) gets the name that you don’t know §

30) BUG

When you try to save workspace variables into a directory that has a LONG pathname (i.e. C:\ Docs and Settings \ ...) exactly more than 259 characters (filename included) then the program will say that the variable you want to save IS NOT in the workspace. Id est, it doesn’t exist even though it ACTUALLY DOES. SOLUTION Simply reduce the name length of the file and the pathname. J

31) To change/reduce the dimension order of a tensor.
A has 4 dimensions.
>> B = permute(A, [3 2 1 4]); The dimensions will be reordered as 1st à 3rd ; 2nd à 2nd ; 3rd à 1st ; 4th à 4th.
If a do: B = permute(mean(A,1), [3 2 1 4]); then I’m reducing one entire dimension to an integer. To reduce that from the tensor, I move that dimension to the end using permute.

Alternative: to reduce singletons (size(A,dim)==1): Let’s say that size(A) = 2 2 1 2;
>> squeeze(A) -> [2 2 2]

33) To plot a graph without actually showing the values in both axis do:
>> set(gca,'xtick',[]); set(gca,'ytick',[]);

34) To change from cell to text:
>> char();

35) Reverse the order of a vector or matrix:
>> flipud();fliplr()

7) Sort by rows:
>> sortrows();

8) Add title to a legend: “Rainfall rates [in/hr]” in this case.
>> h = legend('6.0','4.0','3.5','3.1','2.8','...','Location','SouthEast');
>> v = get(h,'title');
>> set(v,'string','Rainfall Rates [in/hr]','BackgroundColor',[.7 .9 .7],'FontWeight','bold');

9) Use a vector as a legend and add text (“mm/hr” in this case)
>> legend([num2str(VECTOR) repmat(' mm/hr',length(VECTOR),1) ])

10) Solve numerically a ODE but with changing variables. Use anonymous functions. Note that only z,v are declared variables, while the others come from the workspace.
>> [z,v] = ode45((@(z,v) (3*Cd*pa/(4*d*pw)) * (v - (uo * (z/zo).^n))), [H 10 0],vv);

11) Recover “Centered and Scaled” variables while fitting a curve. The original variables are “x” and “y”. “pol_y” is the fitted polynomial
>> z = (x(i)-mean(x))/std(x);
>> rain = polyval(pol_y,z)

12) Multiply a matrix row-wise by vector “x” elements. In this case the sum of the rows
>> x = repmat(1./ sum(WATT'),size(WATT,2),1)'; A = x .* A;

13) Count the number of open figures
>> num_figs = length(findobj('Type','figure'));

14) Plot with secondary axis
>> plotyy(ext,hip./gab,ext,gab-hip);

15) Use the same random stream at each simulation. Some pdfs depend either on rand or randn or both so both generators states need to be set to a given number between 0 and 232
>> rand('state',0); randn('state',0);

16) …Change the lines types, colors and markers of an existing plot or
>>  p1 = plot(x,y);
>>  L = {'--';'-';'--';'-';'--';'-';'-';'-';'-'}; M = {'^';'^';'o';'o';'*';'*';'d';'p';'s'}; C = {'b';'b';'g';'g';'r';'r';'k';'c';'y'};
>>  set(p1,{'LineStyle'},L,{'Marker'},M,{'Color'},C); ☺

17)  String comparison
>>  strcmp('str1', 'str2')

18) Reorder legend entries
>> ha = area(x,y);
>> order = [9:-1:1];
>> h1={'a','b','c','d'};
>> legend(ha(order),h1{order});

19) Salve a string cell as text.
>>fid = fopen('trngsetG.txt','wt');
>>for i = 1 : size(trngset,1)
fprintf(fid,'%s\t %s\t %s\t %s\t %s\t %s\t\n',trngset{i,:});
end
>>fclose(fid);

20) Solve an equation for a single variable in symbolically (despejar x)
>> syms x;
>> f = …
>> solve(f,x)

21) Find the minimum or maximum of a multi-dimensional array

>> X = rand([2,3,4,5]);
>> [min_val, position] = min(X(:));
>> [i,j,k,l] = ind2sub(size(X),position);

22) Nonlinear Regression of measured data with a given model (in this case is a mixture of 2 hyperbolic tangent models)

modelFun =  @(p,x) p(1) .* (tanh((x - p(2)) ./ p(4))- tanh((x - p(3)) ./ p(5)));
startingVals = [4 17 28 3 2];
drops = 1:38; drops = drops(:);
y = [0.2086    0.1484    0.1579    0.340... % These is the data to fit...has 38 elements
coefEsts = nlinfit(drops, y, modelFun, startingVals)
xgrid = linspace(1,38,38);
line(xgrid, modelFun(coefEsts2, xgrid), 'Color','g'); hold
plot(drops,y,'o')

23) Convert symbolic expression to double precision numbers

>> vpa(symb_exp);

24) Smooth a function

>> y = smooth(x,'lowess'); % lowess is a smoothing criteria. There are more available.

25) Find something inside a cell

>> [truefalse, index] = ismember(Cell,'FindThis');

26) Substitute a value in a symbolic expression

>> subs(f_x,x,1);

27) Interpolate a value between 2 values of a vector (equation).

>> VPoints1 = interp1(winds,VPoints,wind_of_interest); % winds is “x”, VPoints is our function f(x), and winds_of… is value not in “x” for which we want to find the value in VPoints.

28) Save a TIFF figure with resolution of 300 dpi from current figure.

>> print -dtiff -r300 picture1
Another option:
>> I = getframe(gcf);
>> imwrite(I.cdata,'figure.tif', 'Resolution', 300)

29) Assign values to multiple variables at the same time.

>> [v1, v2, v3] = deal(x1, x2, x3);

30) Compare changes in 2 codes
>> visdiff('fname1', 'fname2');

31) Set graphic properties in a double-axis plot. Common actions: Modify LineWidth,
>> [ax,h1,h2] = plotyy(x1,y1,x2,y2,’plot’);
>> set(gca,'XTick', linspace(0,30,6))
>> set(h1,'LineStyle','-','Marker','o','LineWidth',3);
>> set(h2,'LineStyle','-','Marker','o','LineWidth',3);
>> set(get(ax(1),'Ylabel'),'String','Label Goes Here!!!')
>> set(get(ax(2),'Ylabel'),'String','Label Goes Here!!!')
>> set(ax([1 2]),'XTick', linspace(50,130,9)); <- Set the number of ticks in the x-axis (yes, there’s 2!)
>> set(ax([1 2]),'XLim', [50 130]) <- Set the limits of the x-axis (yes, there’s 2!)
>> axis(ax,'square') <- Both axis have to be set to square…

a) Do you plot
b) Make boundaries tight
ti = get(gca,'TightInset')
set(gca,'Position',[ti(1) ti(2) 1-ti(3)-ti(1) 1-ti(4)-ti(2)]);
set(gca,'units','centimeters')
pos = get(gca,'Position');
ti = get(gca,'TightInset');
set(gcf, 'PaperUnits','centimeters'); set(gcf, 'PaperSize', [pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
set(gcf, 'PaperPositionMode', 'manual'); set(gcf, 'PaperPosition',[0 0 pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);

33) Change Axis Tick Labels with text in a cell “T”
a) Make sure that the number of ticks is the same as the number of elements in the cell T
set(gca,'XTick',linspace(min(OPTd),max(OPTd),length(OPTd)))
b) Assign the cell as axis label
set(gca,'xticklabel',T)

34) Format x-axis to datestring
>> datetick('x','dd/mmm/yy')

35) Functions available for fitting / Library of models.

36) Cumulative distance traveled along a path .
This is a very useful routine. There's another in MatlabCentral "pathdist" but it requires many other routines.
>> x = legs(lat,lon)

37) Auto limit length of lines in editor.

38) Get limits of the plotting area in a figure. Info here
AxesHandle=findobj(gcf,'Type','axes');
pt1 = get(AxesHandle,{'Position','tightinset','PlotBoxAspectRatio'});

39)  Convert Latitude to 0-359 degrees
Val = wrapTo360(Latitude);

40)  Convert and Format a string (in this case to 4 digits integer from sprintf rules)
HHMM = num2str(hhmm,'%04d');

41)Remove blank spaces from string.
StringN = strtrim(StringO);

42)Replicate elements of an array. repelem
If A = [1 2; 3 4], then repelem(A, 2, 3) returns a matrix
containing a 2-by-3 block of each element of A
[1 1 1 2 2 2; ...
1 1 1 2 2 2; ...
3 3 3 4 4 4; ...
3 3 3 4 4 4].

43)Reshape a Matrix
reshape(X,M,N) .