source: trunk/src/plot_field.m @ 186

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

introduction Mesh for histograms in proj_field

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