source: trunk/src/plot_field.m @ 187

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

various bug repairs

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