source: trunk/src/plot_field.m @ 147

Last change on this file since 147 was 147, checked in by gostiaux, 13 years ago

cleaning code for the detection of matlab version.

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