source: trunk/src/plot_field.m @ 191

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

introduce edit boxes to set axis limits. rationalisation of names FixScal?, FixLimits?....
introduce volume scan in calibration procedures

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