source: trunk/src/plot_field.m @ 293

Last change on this file since 293 was 292, checked in by sommeria, 13 years ago

GUI civ patch2 corrected (SmoothingParam?).
uvmatand view_field updated with panels.
read_plot_param removed (replaced by the mostgeneral read_GUI)

File size: 48.2 KB
Line 
1%'plot_field': plot any field with the structure defined in the uvmat package
2%------------------------------------------------------------------------
3%
4%  This function is used by uvmat to plot fields. It automatically chooses the representation
5% appropriate to the input field structure:
6%     2D vector fields are represented by arrows, 2D scalar fields by grey scale images or contour plots, 1D fields are represented by usual plot with (abscissa, ordinate).
7%  The input field structure is first tested by check_field_structure.m,
8%  then split into blocks of related variables  by find_field_indices.m.
9%  The dimensionality of each block is obtained  by this function
10%  considering the presence of variables with the attribute .Role='coord_x'
11%  and/or coord_y and/or coord_z (case of unstructured coordinates), or
12%  dimension variables (case of matrices).
13%
14% function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,htext,PosColorbar)
15%
16% OUPUT:
17% PlotType: type of plot: 'text','line'(curve plot),'plane':2D view,'volume'
18% PlotParamOut: structure, representing the updated  plotting parameters, in case of automatic scaling
19% haxes: handle of the plotting axis, when a new figure is created.
20%
21%INPUT
22%    Data:   structure describing the field to plot
23%         (optional) .ListGlobalAttribute: cell listing the names of the global attributes
24%                    .Att_1,Att_2... : values of the global attributes
25%         (requested)  .ListVarName: list of variable names to select (cell array of  char strings {'VarName1', 'VarName2',...} )
26%         (requested)  .VarDimName: list of dimension names for each element of .ListVarName (cell array of string cells)
27%                      .VarAttribute: cell of attributes for each element of .ListVarName (cell array of structures of the form VarAtt.key=value)
28%         (requested) .Var1, .Var2....: variables (Matlab arrays) with names listed in .ListVarName
29
30%            Variable attribute .Role :
31%    The only variable attribute used for plotting purpose is .Role which can take
32%    the values
33%       Role = 'scalar':  (default) represents a scalar field
34%            = 'coord_x', 'coord_y',  'coord_z': represents a separate set of
35%                        unstructured coordinate x, y  or z
36%            = 'vector': represents a vector field whose number of components
37%                is given by the last dimension (called 'nb_dim')
38%            = 'vector_x', 'vector_y', 'vector_z'  :represents the x, y or z  component of a vector 
39%            = 'warnflag' : provides a warning flag about the quality of data in a 'Field', default=0, no warning
40%            = 'errorflag': provides an error flag marking false data,
41%                   default=0, no error. Different non zero values can represent different criteria of elimination.
42%
43%
44%         additional elements characterizing the projection object (should not be necessary)--
45%            Data.Style : style of projection object
46%            Data.XObject,.YObject: set of coordinates defining the object position;
47%            Data.ProjMode=type of projection ;
48%            Data.ProjAngle=angle of projection;
49%            Data.DX,.DY,.DZ=increments;
50%            Data.MaxY,MinY: min and max Y
51
52%   haxes: handle of the plotting axes to update with the new plot. If this input is absent or not a valid axes handle, a new figure is created.
53%
54%   PlotParam: parameters for plotting, as read on the uvmat or view_field interface (by function 'read_GUI.m')
55%     .Coordinates.CheckFixLimits:=0 (default) adjust axes limit to the X,Y data, =1: preserves the previous axes limits
56%     .Coordinates.CheckFixEqual: =0 (default):automatic adjustment of the graph, keep 1 to 1 aspect ratio for x and y scales.
57%            --scalars--
58%    .Scalar.MaxA: upper bound (saturation color) for the scalar representation, max(field) by default
59%    .Scalar.MinA: lower bound (saturation) for the scalar representation, min(field) by default
60%    .Scalar.CheckFixScal: =0 (default) lower and upper bounds of the scalar representation set to the min and max of the field
61%               =1 lower and upper bound imposed by .AMax and .MinA
62%    .Scalar.CheckBW= 1 black and white representation imposed, =0 by default.
63%    .Scalar.CheckContours= 1: represent scalars by contour plots (Matlab function 'contour'); =0 by default
64%    .IncrA : contour interval
65%            -- vectors--
66%    .Vectors.VecScale: scale for the vector representation
67%    .Vectors.CheckFixVec: =0 (default) automatic length for vector representation, =1: length set by .VecScale
68%    .Vectors.CheckHideFalse= 0 (default) false vectors represented in magenta, =1: false vectors not represented;
69%    .Vectors.CheckHideWarning= 0 (default) vectors marked by warnflag~=0 marked in black, 1: no warning representation;
70%    .Vectors.CheckDecimate4 = 0 (default) all vectors reprtesented, =1: half of  the vectors represented along each coordinate
71%         -- vector color--
72%    .Vectors.ColorCode= 'black','white': imposed color  (default ='blue')
73%                        'rgb', : three colors red, blue, green depending
74%                        on thresholds .colcode1 and .colcode2 on the input  scalar value (C)
75%                        'brg': like rgb but reversed color order (blue, green, red)
76%                        '64 colors': continuous color from blue to red (multijet)
77%    .Vectors.colcode1 : first threshold for rgb, first value for'continuous'
78%    .Vectors.colcode2 : second threshold for rgb, last value (saturation) for 'continuous'
79%    .Vectors.CheckFixedCbounds;  =0 (default): the bounds on C representation are min and max, =1: they are fixed by .Minc and .MaxC
80%    .Vectors.MinC = imposed minimum of the scalar field used for vector color;
81%    .Vectors.MaxC = imposed maximum of the scalar field used for vector color;
82%
83% PosColorbar: if not empty, display a colorbar for B&W images
84%               imposed position of the colorbar (ex [0.821 0.471 0.019 0.445])
85
86%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
87%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
88%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
89%     This file is part of the toolbox UVMAT.
90%
91%     UVMAT is free software; you can redistribute it and/or modify
92%     it under the terms of the GNU General Public License as published by
93%     the Free Software Foundation; either version 2 of the License, or
94%     (at your option) any later version.
95%
96%     UVMAT is distributed in the hope that it will be useful,
97%     but WITHOUT ANY WARRANTY; without even the implied warranty of
98%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
99%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
100%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
101
102function [PlotType,PlotParamOut,haxes]= plot_field(Data,haxes,PlotParam,PosColorbar)
103% use htext: handles of the text edit box (uicontrol)
104% introduce PlotParam.Hold: 'on' or 'off' (for curves)
105%default output
106
107if ~exist('PlotParam','var'),PlotParam=[];end;
108if ~exist('PosColorbar','var'),PosColorbar=[];end;
109PlotType='text'; %default
110PlotParamOut=PlotParam;%default
111Coordinates=[];
112if isfield(PlotParam,'Coordinates')
113Coordinates=PlotParam.Coordinates;
114end
115
116%% test axes and figure
117testnewfig=1;%test to create a new figure (default)
118testzoomaxes=0;%test for the existence of a zoom secondary figure attached to the plotting axes
119if exist('haxes','var')
120    if ishandle(haxes)
121        if isequal(get(haxes,'Type'),'axes')
122            testnewfig=0;
123            AxeData=get(haxes,'UserData');
124            if isfield(AxeData,'ZoomAxes')&& ishandle(AxeData.ZoomAxes)
125                if isequal(get(AxeData.ZoomAxes,'Type'),'axes')
126                    testzoomaxes=1;
127                    zoomaxes=AxeData.ZoomAxes;
128                end
129            end
130        end
131    end
132end
133% if isfield(PlotParam,'text_display_1') && ishandle(PlotParam.text_display_1)
134%     PlotParam=read_plot_param(PlotParam);   
135% end
136% create a new figure and axes if the plotting axes does not exist
137if testnewfig
138    hfig=figure;
139    set(hfig,'Units','normalized')
140    haxes=axes;
141    set(haxes,'position',[0.13,0.2,0.775,0.73])
142     PlotParam.NextPlot='add'; %parameter for plot_profile and plot_his
143else
144    hfig=get(haxes,'parent');
145    set(0,'CurrentFigure',hfig)% the parent of haxes becomes the current figure
146    set(hfig,'CurrentAxes',haxes)%  haxes becomes the current axes of the parent figure
147end
148
149%% check input structure
150if ~isempty(Data)
151    [Data,errormsg]=check_field_structure(Data);
152    if ~isempty(errormsg)
153        msgbox_uvmat('ERROR',['input of plot_field/check_field_structure: ' errormsg])
154        display(['input of plot_field/check_field_structure:: ' errormsg])
155        return
156    end
157
158    %% check the cells of fields :
159    [CellVarIndex,NbDim,VarType,errormsg]=find_field_indices(Data);
160    if ~isempty(errormsg)
161        msgbox_uvmat('ERROR',['input of plot_field/find_field_indices: ' errormsg]);
162        return
163    end
164    index_2D=find(NbDim==2,2);%find 2D fields (at most 2)
165    index_3D=find(NbDim>2,1);
166    if ~isempty(index_3D)
167        if isfield(Data,'NbDim')&& isequal(Data.NbDim,2)
168            index_2D=[index_2D index_3D];
169        else
170        msgbox_uvmat('ERROR','volume plot not implemented yet');
171        return
172        end
173    end
174   
175    index_1D=find(NbDim==1);
176    index_0D=find(NbDim==0);
177   
178        %% set axes properties
179    if isfield(Coordinates,'CheckFixLimits') && isequal(Coordinates.CheckFixLimits,1)  %adjust the graph limits*
180        set(haxes,'XLimMode', 'manual')
181        set(haxes,'YLimMode', 'manual')
182    else
183        set(haxes,'XLimMode', 'auto')
184        set(haxes,'YLimMode', 'auto')
185    end
186    if ~isfield(Coordinates,'CheckFixEqual')&& isfield(Data,'CoordUnit')
187        Coordinates.CheckFixEqual=1;
188    end
189    if isfield(Coordinates,'CheckFixEqual') && isequal(Coordinates.CheckFixEqual,1)
190        set(haxes,'DataAspectRatioMode','manual')
191       set(haxes,'DataAspectRatio',[1 1 1])
192    else
193        set(haxes,'DataAspectRatioMode','auto')%automatic aspect ratio
194    end
195else
196    index_2D=[];
197    index_1D=[];
198    index_0D=[];
199end
200
201%% plot if the input field is valid
202PlotType='text';
203errormsg=[];
204AxeData=get(haxes,'UserData');
205if isempty(index_2D)
206    plot_plane([],[],[],haxes);%removes images or vector plots if any
207else
208    [xx,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex(index_2D),VarType(index_2D),haxes,PlotParam,PosColorbar);
209    AxeData.NbDim=2;
210    if testzoomaxes && isempty(errormsg)
211        [zoomaxes,PlotParamOut,xx,errormsg]=plot_plane(Data,CellVarIndex(index_2D),VarType(index_2D),zoomaxes,PlotParam,PosColorbar);
212        AxeData.ZoomAxes=zoomaxes;
213    end
214    %remove coordinates variables from 1D plot
215    for ivar=1:length(index_1D)
216        if isequal(CellVarIndex{index_1D(ivar)},VarType{index_1D(ivar)}.coord)
217            index_1D(ivar)=0;
218        end
219    end
220    index_1D=find(index_1D);
221end
222
223if isempty(index_1D)
224     plot_profile([],[],[],haxes);%
225else
226        Coordinates=plot_profile(Data,CellVarIndex(index_1D),VarType(index_1D),haxes,PlotParam.Coordinates);%
227        if testzoomaxes
228            [zoomaxes,Coordinates]=plot_profile(Data,CellVarIndex(index_1D),VarType(index_1D),zoomaxes,PlotParam.Coordinates);
229            AxeData.ZoomAxes=zoomaxes;
230        end
231        if ~isempty(Coordinates)
232            PlotParamOut.Coordinates=Coordinates;
233        end
234        PlotType='line';
235end
236htext=findobj(hfig,'Tag','text_display');
237if ~isempty(htext)
238    if isempty(index_0D)
239        set(htext,'String',{''})
240    else
241        [errormsg]=plot_text(Data,CellVarIndex(index_0D),htext);
242    end
243end
244
245if ~isempty(errormsg)
246    msgbox_uvmat('ERROR', errormsg)
247end
248if isfield(PlotParamOut,'MinX')
249    AxeData.RangeX=[PlotParamOut.MinX PlotParamOut.MaxX];%'[PlotParamOut.MinX PlotParamOut.MaxX];
250    AxeData.RangeY=[PlotParamOut.MinY PlotParamOut.MaxY];%[PlotParamOut.MinY PlotParamOut.MaxY]
251end
252
253%% update the parameters stored in AxeData
254set(haxes,'UserData',AxeData)
255
256%% update the plotted field stored in parent figure
257FigData=get(hfig,'UserData');
258tagaxes=get(haxes,'tag');
259if isfield(FigData,tagaxes)
260    eval(['FigData.' tagaxes '=Data;'])
261    set(hfig,'UserData',FigData)
262end
263
264%-------------------------------------------------------------------
265function errormsg=plot_text(FieldData,CellVarIndex,htext)
266%-------------------------------------------------------------------
267errormsg=[];
268txt_cell={};
269for icell=1:length(CellVarIndex)
270    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
271    for ivar=1:length(VarIndex)
272         VarName=FieldData.ListVarName{VarIndex(ivar)};
273         VarValue=FieldData.(VarName);
274         if size(VarValue,1)~=1
275             VarValue=VarValue';
276         end
277         txt=[VarName '=' num2str(VarValue)];
278         txt_cell=[txt_cell;{txt}];
279    end
280end
281set(htext,'String',txt_cell)
282set(htext,'UserData',txt_cell)% for storage during mouse display
283
284%-------------------------------------------------------------------
285function CoordinatesOut=plot_profile(data,CellVarIndex,VarType,haxes,Coordinates)
286%-------------------------------------------------------------------
287
288if ~exist('Coordinates','var')
289    Coordinates=[];
290end
291CoordinatesOut=Coordinates; %default
292hfig=get(haxes,'parent');
293%suppress existing plot isf empty data
294if isempty(data)
295    hplot=findobj(haxes,'tag','plot_line');
296    if ~isempty(hplot)
297        delete(hplot)
298    end
299    hlegend=findobj(hfig,'tag','legend');
300    if ~isempty(hlegend)
301        delete(hlegend)
302    end
303    return
304end
305
306ColorOrder=[1 0 0;0 0.5 0;0 0 1;0 0.75 0.75;0.75 0 0.75;0.75 0.75 0;0.25 0.25 0.25];
307set(haxes,'ColorOrder',ColorOrder)
308if isfield(Coordinates,'NextPlot')
309    set(haxes,'NextPlot',Coordinates.NextPlot)
310end
311% adjust the size of the plot to include the whole field,
312
313legend_str={};
314
315%% prepare the string for plot command
316plotstr='hhh=plot(';
317coord_x_index=[];
318xtitle='';
319ytitle='';
320test_newplot=1;
321
322%loop on input  fields
323for icell=1:length(CellVarIndex)
324    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list data.ListVarName
325    if ~isempty(VarType{icell}.coord_x)
326        coord_x_index=VarType{icell}.coord_x;
327    else
328        coord_x_index_cell=VarType{icell}.coord(1);
329        if isequal(coord_x_index_cell,0)
330             continue  % the cell has no abscissa, skip it
331        end
332        coord_x_index=coord_x_index_cell;
333    end
334    testplot=ones(size(data.ListVarName));%default test for plotted variables
335    xtitle=[xtitle data.ListVarName{coord_x_index}];
336    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
337    if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=coord_x_index && isfield(data.VarAttribute{coord_x_index},'units')
338        xtitle=[xtitle '(' data.VarAttribute{coord_x_index}.units '), '];
339    else
340        xtitle=[xtitle ', '];
341    end
342    eval(['coord_x{icell}=data.' data.ListVarName{coord_x_index} ';']);%coordinate variable set as coord_x
343    XMin(icell)=min(coord_x{icell});
344    XMax(icell)=max(coord_x{icell});
345    testplot(coord_x_index)=0;
346    if ~isempty(VarType{icell}.ancillary')
347        testplot(VarType{icell}.ancillary)=0;
348    end
349    if ~isempty(VarType{icell}.warnflag')
350        testplot(VarType{icell}.warnflag)=0;
351    end
352    if isfield(data,'VarAttribute')
353        VarAttribute=data.VarAttribute;
354        for ivar=1:length(VarIndex)
355            if length(VarAttribute)>=VarIndex(ivar) && isfield(VarAttribute{VarIndex(ivar)},'long_name')
356                plotname{VarIndex(ivar)}=VarAttribute{VarIndex(ivar)}.long_name;
357            else
358                plotname{VarIndex(ivar)}=data.ListVarName{VarIndex(ivar)};%name for display in plot A METTRE
359            end
360        end
361    end
362    if ~isempty(VarType{icell}.discrete')
363        charplot_0='''+''';
364    else
365        charplot_0='''-''';
366    end
367    YMin=0;
368    YMax=1;%default
369    for ivar=1:length(VarIndex)
370        if testplot(VarIndex(ivar))
371            VarName=data.ListVarName{VarIndex(ivar)};
372            ytitle=[ytitle VarName];
373            if isfield(data,'VarAttribute')&& numel(data.VarAttribute)>=VarIndex(ivar) && isfield(data.VarAttribute{VarIndex(ivar)},'units')
374                ytitle=[ytitle '(' data.VarAttribute{VarIndex(ivar)}.units '), '];
375            else
376                ytitle=[ytitle ', '];
377            end
378            eval(['data.' VarName '=squeeze(data.' VarName ');'])
379            %eval(['min(data.' VarName ')'])
380            eval(['YMin(ivar)=min(min(data.' VarName '));'])
381            eval(['YMax(ivar)=max(max(data.' VarName '));'])
382            plotstr=[plotstr 'coord_x{' num2str(icell) '},data.' VarName ',' charplot_0 ','];
383            eval(['nbcomponent2=size(data.' VarName ',2);']);
384            eval(['nbcomponent1=size(data.' VarName ',1);']);
385            if numel(coord_x{icell})==2
386                coord_x{icell}=linspace(coord_x{icell}(1),coord_x{icell}(2),nbcomponent1);
387            end
388            if nbcomponent1==1|| nbcomponent2==1
389                legend_str=[legend_str {VarName}]; %variable with one component
390            else  %variable with severals  components
391                for ic=1:min(nbcomponent1,nbcomponent2)
392                    legend_str=[legend_str [VarName '_' num2str(ic)]]; %variable with severals  components
393                end                                                   % labeled by their index (e.g. color component)
394            end
395        end
396    end
397    YMin_cell(icell)=min(YMin);
398    YMax_cell(icell)=max(YMax);
399end
400
401%% activate the plot
402if test_newplot && ~isequal(plotstr,'hhh=plot(') 
403    set(hfig,'CurrentAxes',haxes)
404    tag=get(haxes,'tag');   
405    %%%
406    plotstr=[plotstr '''tag'',''plot_line'');'];   
407    eval(plotstr)                  %execute plot (instruction  plotstr)
408    %%%
409    set(haxes,'tag',tag)
410    grid(haxes, 'on')
411    hxlabel=xlabel(xtitle(1:end-2));% xlabel (removes ', ' at the end)
412    set(hxlabel,'Interpreter','none')% desable tex interpreter
413    if length(legend_str)>=1
414        hylabel=ylabel(ytitle(1:end-2));% ylabel (removes ', ' at the end)
415        set(hylabel,'Interpreter','none')% desable tex interpreter
416    end
417    if ~isempty(legend_str)
418        hlegend=findobj(hfig,'Tag','legend');
419        if isempty(hlegend)
420            hlegend=legend(legend_str);
421            txt=ver('MATLAB');
422            Release=txt.Release;
423            relnumb=str2double(Release(3:4));% should be changed to Version for better compatibility
424            if relnumb >= 14
425                set(hlegend,'Interpreter','none')% desable tex interpreter
426            end
427        else
428            legend_old=get(hlegend,'String');
429            if isequal(size(legend_old,1),size(legend_str,1))&&~isequal(legend_old,legend_str)
430                set(hlegend,'String',[legend_old legend_str]);
431            end
432        end
433    end
434    title_str='';
435    if isfield(data,'filename')
436       [Path, title_str, ext]=fileparts(data.filename);
437       title_str=[title_str ext];
438    end
439    if isfield(data,'Action')
440        if ~isequal(title_str,'')
441            title_str=[title_str ', '];
442        end
443        title_str=[title_str data.Action];
444    end
445    htitle=title(title_str);
446    txt=ver('MATLAB');
447    Release=txt.Release;
448    relnumb=str2double(Release(3:4));
449    if relnumb >= 14
450        set(htitle,'Interpreter','none')% desable tex interpreter
451    end
452end
453
454%% determine axes bounds
455CoordinatesOut.RangeX=[min(XMin) max(XMax)];
456CoordinatesOut.RangeY=[min(YMin_cell) max(YMax_cell)];
457fix_lim=isfield(Coordinates,'FixLimits') && Coordinates.FixLimits;
458if fix_lim
459    if ~isfield(Coordinates,'MinX')||~isfield(Coordinates,'MaxX')||~isfield(Coordinates,'MinY')||~isfield(Coordinates,'MaxY')
460        fix_lim=0; %free limits if lits are not set,
461    end
462end
463if ~fix_lim
464    CoordinatesOut.MinX=min(XMin);
465    CoordinatesOut.MaxX=max(XMax);
466    CoordinatesOut.MinY=min(YMin_cell);
467    CoordinatesOut.MaxY=max(YMax_cell);
468end
469
470%-------------------------------------------------------------------
471function [haxes,PlotParamOut,PlotType,errormsg]=plot_plane(Data,CellVarIndex,VarTypeCell,haxes,PlotParam,PosColorbar)
472%-------------------------------------------------------------------
473grid(haxes, 'off')
474%default plotting parameters
475PlotType='plane';%default
476if ~exist('PlotParam','var')
477    PlotParam=[];
478end
479if ~isfield(PlotParam,'Scalar')
480    PlotParam.Scalar=[];
481end
482if ~isfield(PlotParam,'Vectors')
483    PlotParam.Vectors=[];
484end
485
486PlotParamOut=PlotParam;%default
487hfig=get(haxes,'parent');
488hcol=findobj(hfig,'Tag','Colorbar'); %look for colorbar axes
489hima=findobj(haxes,'Tag','ima');% search existing image in the current axes
490errormsg='';%default
491test_ima=0; %default: test for image or map plot
492test_vec=0; %default: test for vector plots
493test_black=0;
494test_false=0;
495test_C=0;
496XName='';
497x_units='';
498YName='';
499y_units='';
500for icell=1:length(CellVarIndex) % length(CellVarIndex) =1 or 2 (from the calling function)
501    VarType=VarTypeCell{icell};
502    ivar_X=VarType.coord_x; % defines (unique) index for the variable representing unstructured x coordinate (default =[])
503    ivar_Y=VarType.coord_y; % defines (unique)index for the variable representing unstructured y coordinate (default =[])
504    ivar_U=VarType.vector_x; % defines (unique) index for the variable representing x vector component (default =[])
505    ivar_V=VarType.vector_y; % defines (unique) index for the variable representing y vector component (default =[])
506    ivar_C=[VarType.scalar VarType.image VarType.color VarType.ancillary]; %defines index (indices) for the scalar or ancillary fields
507    if numel(ivar_C)>1
508        errormsg= 'error in plot_field: too many scalar inputs';
509        return
510    end
511    ivar_F=VarType.warnflag; %defines index (unique) for warning flag variable
512    ivar_FF=VarType.errorflag; %defines index (unique) for error flag variable
513    ind_coord=find(VarType.coord);
514    if numel(ind_coord)==2
515        VarType.coord=VarType.coord(ind_coord);
516    end
517    if ~isempty(ivar_U) && ~isempty(ivar_V)% vector components detected
518        if test_vec
519            errormsg='error in plot_field: attempt to plot two vector fields';
520            return
521        else
522            test_vec=1;
523            eval(['vec_U=Data.' Data.ListVarName{ivar_U} ';'])
524            eval(['vec_V=Data.' Data.ListVarName{ivar_V} ';'])
525            if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates or structured ones (then ivar_X and ivar_Y empty)
526                XName=Data.ListVarName{ivar_X};
527                YName=Data.ListVarName{ivar_Y};
528                eval(['vec_X=reshape(Data.' XName ',[],1);'])
529                eval(['vec_Y=reshape(Data.' YName ',[],1);'])
530            elseif numel(VarType.coord)==2 && ~isequal(VarType.coord,[0 0]);%coordinates defines by dimension variables
531                eval(['y=Data.' Data.ListVarName{VarType.coord(1)} ';'])
532                eval(['x=Data.' Data.ListVarName{VarType.coord(2)} ';'])
533                if numel(y)==2 % y defined by first and last values on aregular mesh
534                    y=linspace(y(1),y(2),size(vec_U,1));
535                end
536                if numel(x)==2 % y defined by first and last values on aregular mesh
537                    x=linspace(x(1),x(2),size(vec_U,2));
538                end
539                [vec_X,vec_Y]=meshgrid(x,y); 
540            else
541                errormsg='error in plot_field: invalid coordinate definition for vector field';
542                return
543            end
544            if ~isempty(ivar_C)
545                 eval(['vec_C=Data.' Data.ListVarName{ivar_C} ';']) ;
546                 vec_C=reshape(vec_C,1,numel(vec_C));
547                 test_C=1;
548            end
549            if ~isempty(ivar_F)%~(isfield(PlotParam.Vectors,'HideWarning')&& isequal(PlotParam.Vectors.HideWarning,1))
550                if test_vec
551                    eval(['vec_F=Data.' Data.ListVarName{ivar_F} ';']) % warning flags for  dubious vectors
552                    if  ~(isfield(PlotParam.Vectors,'HideWarning') && isequal(PlotParam.Vectors.HideWarning,1))
553                        test_black=1;
554                    end
555                end
556            end
557            if ~isempty(ivar_FF) %&& ~test_false
558                if test_vec% TODO: deal with FF for structured coordinates
559                    eval(['vec_FF=Data.' Data.ListVarName{ivar_FF} ';']) % flags for false vectors
560                end
561            end
562        end
563    elseif ~isempty(ivar_C) %scalar or image
564        if test_ima
565             errormsg='attempt to plot two scalar fields or images';
566            return
567        end
568        eval(['A=squeeze(Data.' Data.ListVarName{ivar_C} ');']) ;% scalar represented as color image
569        test_ima=1;
570        if ~isempty(ivar_X) && ~isempty(ivar_Y)% 2D field (with unstructured coordinates  (then ivar_X and ivar_Y not empty)
571            A=reshape(A,1,[]);
572            XName=Data.ListVarName{ivar_X};
573            YName=Data.ListVarName{ivar_Y};
574            eval(['AX=reshape(Data.' XName ',1,[]);'])
575            eval(['AY=reshape(Data.' YName ',1,[]);'])
576            [A,AX,AY]=proj_grid(AX',AY',A',[],[],'np>256');  % interpolate on a grid 
577            if isfield(Data,'VarAttribute')
578                if numel(Data.VarAttribute)>=ivar_X && isfield(Data.VarAttribute{ivar_X},'units')
579                    x_units=[' (' Data.VarAttribute{ivar_X}.units ')'];
580                end
581                if numel(Data.VarAttribute)>=ivar_Y && isfield(Data.VarAttribute{ivar_Y},'units')
582                    y_units=[' (' Data.VarAttribute{ivar_Y}.units ')'];
583                end
584            end       
585        elseif numel(VarType.coord)==2 %structured coordinates
586            XName=Data.ListVarName{VarType.coord(2)};
587            YName=Data.ListVarName{VarType.coord(1)};
588            eval(['AY=Data.' Data.ListVarName{VarType.coord(1)} ';'])
589            eval(['AX=Data.' Data.ListVarName{VarType.coord(2)} ';'])
590            test_interp_X=0; %default, regularly meshed X coordinate
591            test_interp_Y=0; %default, regularly meshed Y coordinate
592            if isfield(Data,'VarAttribute')
593                if numel(Data.VarAttribute)>=VarType.coord(2) && isfield(Data.VarAttribute{VarType.coord(2)},'units')
594                    x_units=Data.VarAttribute{VarType.coord(2)}.units;
595                end
596                if numel(Data.VarAttribute)>=VarType.coord(1) && isfield(Data.VarAttribute{VarType.coord(1)},'units')
597                    y_units=Data.VarAttribute{VarType.coord(1)}.units;
598                end
599            end 
600            if numel(AY)>2
601                DAY=diff(AY);
602                DAY_min=min(DAY);
603                DAY_max=max(DAY);
604                if sign(DAY_min)~=sign(DAY_max);% =1 for increasing values, 0 otherwise
605                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(1)} ];
606                      return
607                end
608                test_interp_Y=(DAY_max-DAY_min)> 0.0001*abs(DAY_max);
609            end
610            if numel(AX)>2
611                DAX=diff(AX);
612                DAX_min=min(DAX);
613                DAX_max=max(DAX);
614                if sign(DAX_min)~=sign(DAX_max);% =1 for increasing values, 0 otherwise
615                     errormsg=['errror in plot_field.m: non monotonic dimension variable ' Data.ListVarName{VarType.coord(2)} ];
616                      return
617                end
618                test_interp_X=(DAX_max-DAX_min)> 0.0001*abs(DAX_max);
619            end 
620            if test_interp_Y         
621                npxy(1)=max([256 floor((AY(end)-AY(1))/DAY_min) floor((AY(end)-AY(1))/DAY_max)]);
622                yI=linspace(AY(1),AY(end),npxy(1));
623                if ~test_interp_X
624                    xI=linspace(AX(1),AX(end),size(A,2));%default
625                    AX=xI;
626                end
627            end
628            if test_interp_X 
629                npxy(2)=max([256 floor((AX(end)-AX(1))/DAX_min) floor((AX(end)-AX(1))/DAX_max)]);
630                xI=linspace(AX(1),AX(end),npxy(2));   
631                if ~test_interp_Y
632                   yI=linspace(AY(1),AY(end),size(A,1));
633                   AY=yI;
634                end
635            end
636            if test_interp_X || test_interp_Y               
637                [AX2D,AY2D]=meshgrid(AX,AY);
638                A=interp2(AX2D,AY2D,double(A),xI,yI');
639            end
640            AX=[AX(1) AX(end)];% keep only the lower and upper bounds for image represnetation
641            AY=[AY(1) AY(end)];
642        else
643            errormsg='error in plot_field: invalid coordinate definition ';
644            return
645        end
646    end
647    %define coordinates as CoordUnits, if not defined as attribute for each variable
648    if isfield(Data,'CoordUnit')
649        if isempty(x_units)
650            x_units=Data.CoordUnit;
651        end
652        if isempty(y_units)
653            y_units=Data.CoordUnit;
654        end
655    end
656       
657end
658
659%%   image or scalar plot %%%%%%%%%%%%%%%%%%%%%%%%%%
660
661if ~isfield(PlotParam.Scalar,'CheckContours')
662    PlotParam.Scalar.Contours=0; %default
663end
664PlotParamOut=PlotParam; %default
665if test_ima
666    % distinguish B/W and color images
667    np=size(A);%size of image
668    siz=numel(np);
669    if siz>3
670       errormsg=['unrecognized scalar type: ' num2str(siz) ' dimensions'];
671            return
672    end
673    if siz==3
674        if np(3)==1
675            siz=2;%B W image
676        elseif np(3)==3
677            siz=3;%color image
678        else
679            errormsg=['unrecognized scalar type in plot_field: considered as 2D field with ' num2str(np(3)) ' color components'];
680            return
681        end
682    end
683   
684    %set the color map
685    if isfield(PlotParam.Scalar,'BW')
686        BW=PlotParam.Scalar.BW; %test for BW gray scale images
687    else
688        BW=(siz==2) && (isa(A,'uint8')|| isa(A,'uint16'));% non color images represented in gray scale by default
689    end
690   
691    %case of grey level images or contour plot
692    if siz==2
693        if ~isfield(PlotParam.Scalar,'FixScal')
694            PlotParam.Scalar.FixScal=0;%default
695        end
696        if ~isfield(PlotParam.Scalar,'MinA')
697            PlotParam.Scalar.MinA=[];%default
698        end
699        if ~isfield(PlotParam.Scalar,'MaxA')
700            PlotParam.Scalar.MaxA=[];%default
701        end
702        Aline=[];
703        if isequal(PlotParam.Scalar.FixScal,0)||isempty(PlotParam.Scalar.MinA)||~isa(PlotParam.Scalar.MinA,'double')  %correct if there is no numerical data in edit box
704            Aline=reshape(A,1,[]);
705            Aline=Aline(~isnan(A));
706            if isempty(Aline)
707                 errormsg='NaN input scalar or image in plot_field';
708                return
709            end
710            MinA=double(min(Aline));
711            %MinA=double(min(min(A)));
712        else
713            MinA=PlotParam.Scalar.MinA;
714        end;
715        if isequal(PlotParam.Scalar.FixScal,0)||isempty(PlotParam.Scalar.MaxA)||~isa(PlotParam.Scalar.MaxA,'double') %correct if there is no numerical data in edit box
716            if isempty(Aline)
717               Aline=reshape(A,1,[]);
718               Aline=Aline(~isnan(A));
719               if isempty(Aline)
720                 errormsg='NaN input scalar or image in plot_field';
721                return
722               end
723            end
724            MaxA=double(max(Aline));
725           % MaxA=double(max(max(A)));
726        else
727            MaxA=PlotParam.Scalar.MaxA; 
728        end;
729        PlotParamOut.Scalar.MinA=MinA;
730        PlotParamOut.Scalar.MaxA=MaxA;
731       
732        % case of contour plot
733        if isequal(PlotParam.Scalar.Contours,1)
734            if ~isempty(hima) && ishandle(hima)
735                delete(hima)
736            end
737            if ~isfield(PlotParam.Scalar,'IncrA')
738                PlotParam.Scalar.IncrA=NaN;
739            end
740            if isnan(PlotParam.Scalar.IncrA)% | PlotParam.Scalar.AutoScal==0
741                cont=colbartick(MinA,MaxA);
742                intercont=cont(2)-cont(1);%default
743                PlotParamOut.Scalar.IncrA=intercont;
744            else
745               intercont=PlotParam.Scalar.IncrA;
746            end
747            B=A;           
748            abscontmin=intercont*floor(MinA/intercont);
749            abscontmax=intercont*ceil(MaxA/intercont);
750            contmin=intercont*floor(min(min(B))/intercont);
751            contmax=intercont*ceil(max(max(B))/intercont);
752            cont_pos_plus=0:intercont:contmax;
753            cont_pos_min=double(contmin):intercont:-intercont;
754            cont_pos=[cont_pos_min cont_pos_plus];
755            sizpx=(AX(end)-AX(1))/(np(2)-1);
756            sizpy=(AY(1)-AY(end))/(np(1)-1);
757            x_cont=AX(1):sizpx:AX(end); % pixel x coordinates for image display
758            y_cont=AY(1):-sizpy:AY(end); % pixel x coordinates for image display
759           % axes(haxes)% set the input axes handle as current axis
760    txt=ver('MATLAB');
761    Release=txt.Release;
762            relnumb=str2double(Release(3:4));
763            if relnumb >= 14
764                    vec=linspace(0,1,(abscontmax-abscontmin)/intercont);%define a greyscale colormap with steps intercont
765                map=[vec' vec' vec'];
766                colormap(map);
767                [var,hcontour]=contour(x_cont,y_cont,B,cont_pos);       
768                set(hcontour,'Fill','on')
769                set(hcontour,'LineStyle','none')
770                hold on
771            end
772            [var_p,hcontour_p]=contour(x_cont,y_cont,B,cont_pos_plus,'k-');
773            hold on
774            [var_m,hcontour_m]=contour(x_cont,y_cont,B,cont_pos_min,':');
775            set(hcontour_m,'LineColor',[1 1 1])
776            hold off
777            caxis([abscontmin abscontmax])
778            colormap(map);
779        end
780       
781        % set  colormap for  image display
782        if ~isequal(PlotParam.Scalar.Contours,1) 
783            % rescale the grey levels with min and max, put a grey scale colorbar
784            B=A;
785            if BW
786                vec=linspace(0,1,255);%define a linear greyscale colormap
787                map=[vec' vec' vec'];
788                colormap(map);  %grey scale color map
789            else
790                colormap('default'); % standard faulse colors for div, vort , scalar fields
791            end
792        end
793       
794    % case of color images
795    else
796        if BW
797            B=uint16(sum(A,3));
798        else
799            B=uint8(A);
800        end
801        MinA=0;
802        MaxA=255;
803    end
804   
805    % display usual image
806    if ~isequal(PlotParam.Scalar.Contours,1)     
807        % interpolate field to increase resolution of image display
808        test_interp=1;
809        if max(np) <= 64
810            npxy=8*np;% increase the resolution 8 times
811        elseif max(np) <= 128
812            npxy=4*np;% increase the resolution 4 times
813        elseif max(np) <= 256
814            npxy=2*np;% increase the resolution 2 times
815        else
816            npxy=np;
817            test_interp=0; % no interpolation done
818        end
819        if test_interp==1%if we interpolate   
820            x=linspace(AX(1),AX(2),np(2));
821            y=linspace(AY(1),AY(2),np(1));
822            [X,Y]=meshgrid(x,y);
823            xi=linspace(AX(1),AX(2),npxy(2));
824            yi=linspace(AY(1),AY(2),npxy(1));
825            B = interp2(X,Y,double(B),xi,yi');
826        end           
827        % create new image if there  no image handle is found
828        if isempty(hima)
829            tag=get(haxes,'Tag');
830            if MinA<MaxA
831                hima=imagesc(AX,AY,B,[MinA MaxA]);
832            else % to deal with uniform field
833                hima=imagesc(AX,AY,B,[MaxA-1 MaxA]);
834            end
835            set(hima,'Tag','ima','HitTest','off')
836            set(haxes,'Tag',tag);%preserve the axes tag (removed by image fct !!!)     
837            uistack(hima, 'bottom')
838        % update an existing image
839        else
840            set(hima,'CData',B);
841            if MinA<MaxA
842                set(haxes,'CLim',[MinA MaxA])
843            else
844                set(haxes,'CLim',[MinA MaxA+1])
845            end
846            set(hima,'XData',AX);
847            set(hima,'YData',AY);
848        end
849    end
850    test_ima=1;
851   
852    %display the colorbar code for B/W images if Poscolorbar not empty
853    if siz==2 && exist('PosColorbar','var')&& ~isempty(PosColorbar)
854        if isempty(hcol)||~ishandle(hcol)
855             hcol=colorbar;%create new colorbar
856        end
857        if length(PosColorbar)==4
858                 set(hcol,'Position',PosColorbar)           
859        end
860        %YTick=0;%default
861        if MaxA>MinA
862            if isequal(PlotParam.Scalar.Contours,1)
863                colbarlim=get(hcol,'YLim');
864                scale_bar=(colbarlim(2)-colbarlim(1))/(abscontmax-abscontmin);               
865                YTick=cont_pos(2:end-1);
866                YTick_scaled=colbarlim(1)+scale_bar*(YTick-abscontmin);
867                set(hcol,'YTick',YTick_scaled);
868            elseif (isfield(PlotParam.Scalar,'BW') && isequal(PlotParam.Scalar.BW,1))||isa(A,'uint8')|| isa(A,'uint16')%images
869                hi=get(hcol,'children');
870                if iscell(hi)%multiple images in colorbar
871                    hi=hi{1};
872                end
873                set(hi,'YData',[MinA MaxA])
874                set(hi,'CData',(1:256)')
875                set(hcol,'YLim',[MinA MaxA])
876                YTick=colbartick(MinA,MaxA);
877                set(hcol,'YTick',YTick)               
878            else
879                hi=get(hcol,'children');
880                if iscell(hi)%multiple images in colorbar
881                    hi=hi{1};
882                end
883                set(hi,'YData',[MinA MaxA])
884                set(hi,'CData',(1:64)')
885                YTick=colbartick(MinA,MaxA);
886                set(hcol,'YLim',[MinA MaxA])
887                set(hcol,'YTick',YTick)
888            end
889            set(hcol,'Yticklabel',num2str(YTick'));
890        end
891    elseif ishandle(hcol)
892        delete(hcol); %erase existing colorbar if not needed
893    end
894else%no scalar plot
895    if ~isempty(hima) && ishandle(hima)
896        delete(hima)
897    end
898    if ~isempty(hcol)&& ishandle(hcol)
899       delete(hcol)
900    end
901    PlotParamOut=rmfield(PlotParamOut,'Scalar');
902end
903
904%%   vector plot %%%%%%%%%%%%%%%%%%%%%%%%%%
905if test_vec
906   %vector scale representation
907    if size(vec_U,1)==numel(vec_Y) && size(vec_U,2)==numel(vec_X); % x, y  coordinate variables
908        [vec_X,vec_Y]=meshgrid(vec_X,vec_Y);
909    end   
910    vec_X=reshape(vec_X,1,numel(vec_X));%reshape in matlab vectors
911    vec_Y=reshape(vec_Y,1,numel(vec_Y));
912    vec_U=reshape(vec_U,1,numel(vec_U));
913    vec_V=reshape(vec_V,1,numel(vec_V));
914     MinMaxX=max(vec_X)-min(vec_X);
915    if  isfield(PlotParam.Vectors,'FixVec') && isequal(PlotParam.Vectors.FixVec,1)&& isfield(PlotParam.Vectors,'VecScale')...
916               &&~isempty(PlotParam.Vectors.VecScale) && isa(PlotParam.Vectors.VecScale,'double') %fixed vector scale
917        scale=PlotParam.Vectors.VecScale;  %impose the length of vector representation
918    else
919        if ~test_false %remove false vectors   
920            indsel=1:numel(vec_X);%
921        end
922        if isempty(vec_U)
923            scale=1;
924        else
925            if isempty(indsel)
926                MaxU=max(abs(vec_U));
927                MaxV=max(abs(vec_V));
928            else
929                MaxU=max(abs(vec_U(indsel)));
930                MaxV=max(abs(vec_V(indsel)));
931            end
932            scale=MinMaxX/(max(MaxU,MaxV)*50);
933            PlotParam.Vectors.VecScale=scale;%update the 'scale' display
934        end
935    end
936   
937    %record vectors on the plotting axes
938    if test_C==0
939        vec_C=ones(1,numel(vec_X));
940    end
941   
942    %decimate by a factor 2 in vector mesh(4 in nbre of vectors)
943    if isfield(PlotParam.Vectors,'decimate4') && isequal(PlotParam.Vectors.decimate4,1)
944        diffy=diff(vec_Y); %difference dy=vec_Y(i+1)-vec_Y(i)
945        dy_thresh=max(abs(diffy))/2;
946        ind_jump=find(abs(diffy) > dy_thresh); %indices with diff(vec_Y)> max/2, detect change of line
947        ind_sel=1:ind_jump(1);%select the first line
948        for i=2:2:length(ind_jump)-1
949            ind_sel=[ind_sel (ind_jump(i)+1:ind_jump(i+1))];% select the odd lines
950        end
951        nb_sel=length(ind_sel);
952        ind_sel=ind_sel(1:2:nb_sel);% take half the points on a line
953        vec_X=vec_X(ind_sel);
954        vec_Y=vec_Y(ind_sel);
955        vec_U=vec_U(ind_sel);
956        vec_V=vec_V(ind_sel);
957        vec_C=vec_C(ind_sel);
958        if ~isempty(ivar_F)
959           vec_F=vec_F(ind_sel);
960        end
961        if ~isempty(ivar_FF)
962           vec_FF=vec_FF(ind_sel);
963        end
964    end
965   
966    %get main level color code
967    [colorlist,col_vec,PlotParamOut.Vectors]=set_col_vec(PlotParam.Vectors,vec_C);
968   
969    % take flags into account: add flag colors to the list of colors
970    sizlist=size(colorlist);
971    nbcolor=sizlist(1);
972    if test_black
973       nbcolor=nbcolor+1;
974       colorlist(nbcolor,:)=[0 0 0]; %add black to the list of colors
975       if ~isempty(ivar_FF)
976          %  ind_flag=find(vec_F~=1 & vec_F~=0 & vec_FF==0);  %flag warning but not false
977            col_vec(vec_F~=1 & vec_F~=0 & vec_FF==0)=nbcolor;
978       else
979           % ind_flag=find(vec_F~=1 & vec_F~=0);
980            col_vec(vec_F~=1 & vec_F~=0)=nbcolor;
981       end
982      % col_vec(ind_flag)=nbcolor;   
983    end
984    nbcolor=nbcolor+1;
985    if ~isempty(ivar_FF)
986        %ind_flag=find(vec_FF~=0);
987        if isfield(PlotParam.Vectors,'HideFalse') && PlotParam.Vectors.HideFalse==1
988            colorlist(nbcolor,:)=[NaN NaN NaN];% no plot of false vectors
989        else
990            colorlist(nbcolor,:)=[1 0 1];% magenta color
991        end
992        col_vec(vec_FF~=0)=nbcolor;
993    end
994    %plot vectors:
995    quiresetn(haxes,vec_X,vec_Y,vec_U,vec_V,scale,colorlist,col_vec);   
996
997else
998    hvec=findobj(haxes,'Tag','vel');
999    if ~isempty(hvec)
1000        delete(hvec);
1001    end
1002    PlotParamOut=rmfield(PlotParamOut,'Vectors');
1003end
1004
1005%listfields={'AY','AX','A','X','Y','U','V','C','W','F','FF'};
1006%listdim={'AY','AX',{'AY','AX'},'nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors','nb_vectors'};
1007%Role={'coord_y','coord_x','scalar','coord_x','coord_y','vector_x','vector_y','scalar','vector_z','warnflag','errorflag'};
1008%ind_select=[];
1009nbvar=0;
1010
1011%store the coordinate extrema occupied by the field
1012if ~isempty(Data)
1013    XMin=[];
1014    XMax=[];
1015    YMin=[];
1016    YMax=[];
1017    fix_lim=isfield(PlotParam,'FixLimits') && PlotParam.FixLimits;
1018    if fix_lim
1019        if ~isfield(PlotParam,'MinX')||~isfield(PlotParam,'MaxX')||~isfield(PlotParam,'MinY')||~isfield(PlotParam,'MaxY')
1020            fix_lim=0; %free limits if limits are not set,
1021        else
1022            XMin=PlotParam.MinX
1023            XMax=PlotParam.MaxX;
1024            YMin=PlotParam.MinY;
1025            YMax=PlotParam.MaxY;
1026        end  %else PlotParamOut.XMin =PlotParam.XMin...
1027    else
1028        if test_ima %both background image and vectors coexist, take the wider bound
1029            XMin=min(AX);
1030            XMax=max(AX);
1031            YMin=min(AY);
1032            YMax=max(AY);
1033            if test_vec
1034                XMin=min(XMin,min(vec_X));
1035                XMax=max(XMax,max(vec_X));
1036                YMin=min(YMin,min(vec_Y));
1037                YMax=max(YMax,max(vec_Y));
1038            end
1039        elseif test_vec
1040            XMin=min(vec_X);
1041            XMax=max(vec_X);
1042            YMin=min(vec_Y);
1043            YMax=max(vec_Y);
1044        end
1045    end
1046%     PlotParamOut.RangeX=[XMin XMax]; %range of x, to be stored in the user data of the plot axes
1047%     PlotParamOut.RangeY=[YMin YMax]; %range of x, to be stored in the user data of the plot axes
1048%     if ~fix_lim
1049        PlotParamOut.MinX=XMin;
1050        PlotParamOut.MaxX=XMax;
1051        PlotParamOut.MinY=YMin;
1052        PlotParamOut.MaxY=YMax;
1053        if XMax>XMin
1054            set(haxes,'XLim',[XMin XMax]);% set x limits of frame in axes coordinates
1055        end
1056        if YMax>YMin
1057            set(haxes,'YLim',[YMin YMax]);% set x limits of frame in axes coordinates
1058        end
1059%     end
1060    set(haxes,'YDir','normal')
1061    set(get(haxes,'XLabel'),'String',[XName ' (' x_units ')']);
1062    set(get(haxes,'YLabel'),'String',[YName ' (' y_units ')']);
1063    PlotParamOut.x_units=x_units;
1064    PlotParamOut.y_units=y_units;
1065end
1066%-------------------------------------------------------------------
1067% --- function for plotting vectors
1068%INPUT:
1069% haxes: handles of the plotting axes
1070% x,y,u,v: vectors coordinates and vector components to plot, arrays withb the same dimension
1071% scale: scaling factor for vector length representation
1072% colorlist(icolor,:): list of vector colors, dim (nbcolor,3), depending on color #i
1073% col_vec: matlab vector setting the color number #i for each velocity vector
1074function quiresetn(haxes,x,y,u,v,scale,colorlist,col_vec)
1075%-------------------------------------------------------------------
1076%define arrows
1077theta=0.5 ;%angle arrow
1078alpha=0.3 ;%length arrow
1079rot=alpha*[cos(theta) -sin(theta); sin(theta) cos(theta)]';
1080%find the existing lines
1081h=findobj(haxes,'Tag','vel');% search existing lines in the current axes
1082sizh=size(h);
1083set(h,'EraseMode','xor');
1084set(haxes,'NextPlot','replacechildren');
1085
1086%drawnow
1087%create lines (if no lines) or modify them
1088if ~isequal(size(col_vec),size(x))
1089    col_vec=ones(size(x));% case of error in col_vec input
1090end
1091sizlist=size(colorlist);
1092ncolor=sizlist(1);
1093
1094for icolor=1:ncolor
1095    %determine the line positions for each color icolor
1096    ind=find(col_vec==icolor);
1097    xc=x(ind);
1098    yc=y(ind);
1099    uc=u(ind)*scale;
1100    vc=v(ind)*scale;
1101    n=size(xc);
1102    xN=NaN*ones(size(xc));
1103    matx=[xc(:)-uc(:)/2 xc(:)+uc(:)/2 xN(:)]';
1104    %     matx=[xc(:) xc(:)+uc(:) xN(:)]';
1105    matx=reshape(matx,1,3*n(2));
1106    maty=[yc(:)-vc(:)/2 yc(:)+vc(:)/2 xN(:)]';
1107    %     maty=[yc(:) yc(:)+vc(:) xN(:)]';
1108    maty=reshape(maty,1,3*n(2));
1109   
1110    %determine arrow heads
1111    arrowplus=rot*[uc;vc];
1112    arrowmoins=rot'*[uc;vc];
1113    x1=xc+uc/2-arrowplus(1,:);
1114    x2=xc+uc/2;
1115    x3=xc+uc/2-arrowmoins(1,:);
1116    y1=yc+vc/2-arrowplus(2,:);
1117    y2=yc+vc/2;
1118    y3=yc+vc/2-arrowmoins(2,:);
1119    matxar=[x1(:) x2(:) x3(:) xN(:)]';
1120    matxar=reshape(matxar,1,4*n(2));
1121    matyar=[y1(:) y2(:) y3(:) xN(:)]';
1122    matyar=reshape(matyar,1,4*n(2));
1123    %draw the line or modify the existing ones
1124    tri=reshape(1:3*length(uc),3,[])';   
1125    isn=isnan(colorlist(icolor,:));%test if color NaN
1126    if 2*icolor > sizh(1) %if icolor exceeds the number of existing ones
1127        if ~isn(1) %if the vectors are visible color not nan
1128            if n(2)>0
1129                hold on
1130                line(matx,maty,'Color',colorlist(icolor,:),'Tag','vel');% plot new lines
1131                line(matxar,matyar,'Color',colorlist(icolor,:),'Tag','vel');% plot arrows
1132            end
1133        end
1134    else
1135        if isn(1)
1136            delete(h(2*icolor-1))
1137            delete(h(2*icolor))
1138        else
1139            set(h(2*icolor-1),'Xdata',matx,'Ydata',maty);
1140            set(h(2*icolor-1),'Color',colorlist(icolor,:));
1141            set(h(2*icolor-1),'EraseMode','xor');
1142            set(h(2*icolor),'Xdata',matxar,'Ydata',matyar);
1143            set(h(2*icolor),'Color',colorlist(icolor,:));
1144            set(h(2*icolor),'EraseMode','xor');
1145        end
1146    end
1147end
1148if sizh(1) > 2*ncolor
1149    for icolor=ncolor+1 : sizh(1)/2%delete additional objects
1150        delete(h(2*icolor-1))
1151        delete(h(2*icolor))
1152    end
1153end
1154
1155%-------------------------------------------------------------------
1156% ---- determine tick positions for colorbar
1157function YTick=colbartick(MinA,MaxA)
1158%-------------------------------------------------------------------
1159%determine tick positions with "simple" values between MinA and MaxA
1160YTick=0;%default
1161maxabs=max([abs(MinA) abs(MaxA)]);
1162if maxabs>0
1163ord=10^(floor(log10(maxabs)));%order of magnitude
1164div=1;
1165siz2=1;
1166while siz2<2
1167%     values=[-9:div:9];
1168    values=-10:div:10;
1169    ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);%indices of 'values' such that MinA<ord*values<MaxA
1170    siz=size(ind);
1171    if siz(2)<4%if there are less than 4 selected values (4 levels)
1172        values=-9:0.5*div:9;
1173        ind=find((ord*values-MaxA)<0 & (ord*values-MinA)>0);
1174    end
1175    siz2=size(ind,2);
1176%     siz2=siz(2)
1177    div=div/10;
1178end
1179YTick=ord*values(ind);
1180end
1181
Note: See TracBrowser for help on using the repository browser.