source: trunk/src/plot_field.m @ 183

Last change on this file since 183 was 179, checked in by sommeria, 14 years ago

various bug repairs, in particular for 3D fields

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