source: trunk/src/plot_field.m @ 185

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

bug repqir for reqding times zith Dtk, coord units displyed in uv,qt

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