Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Saturday, July 18, 2020

Code:多项参考

  1. [Matlab]删除XLS文件特定Sheet或空白Sheet(默认Sheet);
  2. [SPEI_SPI]计算栅格站点;
  3. [Matlab]统计知网关键词词频;
  4. [Matlab]
  5. 1
    2
    3
    4
    5
    % Read Image
    [image, geo]=readgeoraster(imgpath);
    info=georasterinfo(imgpath);
    % Save Image
    geotiffwrite('newimg.tif', image, geo); 
    
    % read a geo-referenced image 
    [image, geo]=readgeoraster(filepath);
    
    try
        info=geotiffinfo(filepath);
    catch
        info=georasterinfo(filepath);
    end
    
    % write a geo-referenced image 
    try
        geotiffwrite(otpath, uint8(class_imag), geo);
    catch
        strcmd=['gdalinfo ', filepath];
        [~, cmdout]=system(strcmd);
        epsg=extractBetween(cmdout, "EPSG:"," got from GeoTIFF keys");
        epsg=epsg{1};
        % geotiffwrite(otpath, uint8(class_imag), geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
        geotiffwrite(otpath, uint8(class_imag), geo, 'CoordRefSysCode', ['EPSG:', epsg]);
    end
    
    1
    geotiffwrite(otpath, uint8(class_imag), geo, 'CoordRefSysCode', ['EPSG:', epsg], 'TiffType', 'bigtiff');
    
    1
    geotiffwrite('m2.tif', image, geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
    
  6. [Matlab] A powerful toolbox for exporting images, refer to the online documentation for usage instructions; to save images and prevent accidents, use export_fig('exportfig_painters.png', '-png', '-painters', '-r300');. When the image contains Chinese characters, refer to this code snippet: export_fig([name,'.png'], '-png', '-r400','-q300');.
  7. [Matlab] Get the parent folder path
  8.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    %==========================================================================================================================
    % Gets the folder one level up.  If startingFolder is a filename with an extension it gets the containing folder and the child folder is null.
    % Returns null for both if the folder does not exist, and it's not a filename either.
    function [parentFolder, childFolder] = GetParentFolder(startingFolder)
    parentFolder = []; % Initialize
    childFolder = []; 
    try
    	if isfolder(startingFolder)
    		[parentFolder, childFolder, ext] = fileparts(startingFolder);
    		% Need to append extension for rare cases where deepest folder has a dot in the name.
    		childFolder = [childFolder, ext];
    	elseif isfile(startingFolder)
    		% It's a filename, not a folder.  Need to change otherwise childFolder will be returned as the base file name.
    		[parentFolder, childFolder, ext] = fileparts(startingFolder);
    		childFolder = []; % No child folder since it's a filename, not a folder name.
    	end
    catch ME
    	message = sprintf('Error in GetParentFolder():\n%s', ME.message);
    	uiwait(msgbox(message));
    end
    return; % from GetParentFolder
    end
    
  9. [Matlab]Export text on a text file.
  10. 1
    2
    3
    4
    fid=fopen(txtpath, 'w', 'n', 'US-ASCII');
    fprintf(fid, '%s\r\n', num2str(value));
    fclose(fid);
    fclose('all');
    
  11. [Matlab]Enhance RGB Image Code.
  12.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    function enhan_image=GenenhanImage(filepath)
    %  https://www.mathworks.com/matlabcentral/fileexchange/64932-files-for-demystifying-deep-learning-semantic-segmentation-and-deployment?s_tid=srchtitle
         % Load the images located in the above path using imageDatstore - ML Function
        imds = imageDatastore(filepath);
        pic_num = 1;
        I_raw = readimage(imds, pic_num);
    
        enhan_image= histeq(uint8(I_raw)); 
    
    end
    
    1
    image=imadjust(image, stretchlim(image), []);
    
  13. [Matlab]To decrease computation time, use GPU processing, if it is available.
  14. 1
    2
    3
    4
    I = imread("peppers.png");
    if(canUseGPU)
        I = gpuArray(I);
    end
    
  15. [Matlab]输出图片的强大Toolbox,用法说明参考在线文档(可能需要翻墙)以export_fig('exportfig_painters.png', '-png', '-painters', '-r300');保存图片,避免意外情况;当图片包含中文字符时参考此段代码export_fig([name,'.png'], '-png', '-r400','-q300');;
  16. [Matlab]Figure全屏命令:set(gcf,'outerposition',get(0,'screensize'));;
  17. A GEO file in latitude-longitude projection.
  18. [Matlab]按比例在Plot上打上文字.
  19.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    % Add Text
    fnum=48;
    loX=0.568;
    laY=0.1;
    GenTextMap(loX, laY, t, fnum);
    
    function GenTextMap(loX, laY, yymm, fnum)
    
        % text(-94.78674012, 53.88222466, "   Island Lake", 'FontSize', 15)
        xxx=get(gca, 'XLim');
        yyy=get(gca, 'YLim');
    
        x=loX*(max(xxx)-min(xxx))+min(xxx);
        y=laY*(max(yyy)-min(yyy))+min(yyy);
    
        text(x, y, yymm, 'FontName', 'Arial', 'FontSize', fnum);
    
    
    
    
    end
    
    fnum=48;
    loX=0.1;
    laY=0.7;
    t=char(ia-1+97+5+5);
    t=['(', t, ')'];
    GenTextMapkk(loX, laY, t, fnum);
    function GenTextMapkk(loX, laY, yymm, fnum)
        xxx=get(gca, 'LatitudeLimits');
        yyy=get(gca, 'LongitudeLimits');
        x=loX*(max(xxx)-min(xxx))+min(xxx);
        y=laY*(max(yyy)-min(yyy))+min(yyy);
        text(x, y, yymm, 'FontName', 'Arial', 'FontSize', fnum);
    end
    
    fnum=90;
            loX=0.85;
            laY=0.5;
            t=dsname;
            GenTextMapCenter(loX, laY, t, fnum)
    function GenTextMapCenter(loX, laY, yymm, fnum)
        xxx=get(gca, 'LatitudeLimits');
        yyy=get(gca, 'LongitudeLimits');
        x=loX*(max(xxx)-min(xxx))+min(xxx);
        y=laY*(max(yyy)-min(yyy))+min(yyy);
        text(x, y, yymm, 'FontName', 'Arial', 'FontSize', fnum, 'HorizontalAlignment', 'center');
    end
    
  20. 世界各国边界(简化).
  21. 替换至NaN
  22. 1
    2
    3
    4
    5
    6
    7
    8
    9
    missing_idx = cellfun(@(x) is_missing(x), rawdat, 'UniformOutput', true);
    rawdat(missing_idx) = {NaN};
    
    function tf = is_missing(x)
        tf = false;
        if ismissing(x)
            tf = true;
        end
    end
    
  23. 自制图例
  24. 1
    2
    3
    4
    5
    6
    7
    8
    9
    % Add legend
    h = gobjects(3, 1);  % preallocate graphic handles
    h(1)=plot(-100, -100, 'hexagram', 'MarkerSize', 6, 'LineWidth', 1, 'MarkerEdgeColor', 'k', ...
        'MarkerFaceColor', 'none');
    h(2)=plot(-100, -100, 'o', 'MarkerSize', 6, 'LineWidth', 1, 'MarkerEdgeColor', 'none', ...
        'MarkerFaceColor', 'r');
    h(3)=plot(-100, -100, 'o', 'MarkerSize', 6, 'LineWidth', 1, 'MarkerEdgeColor', 'b', ...
        'MarkerFaceColor', 'none');
    legend(h, labels, 'Location', 'northwest');  % call once after the loop
    
  25. Convert a cell array of datetime to an array of datetime
  26. datcol=[datcol{:}];
    datcol=datcol';
    
  27. Multipal Plots
  28. Nh=4;
    Nw=17;
    gap=[0.00, 0.01];
    marg_h=[0.20];
    marg_w=0.05;
    figure;
    ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w);
    set(gcf,'outerposition',get(0,'screensize'));
    
    
  29. annotation
  30. annotation('textbox', [0.1 0.936 0.8 0.06], ...
        'String', {'Number of Hours with PM2.5 Concentrations Exceeding 15 µg/m³ at Each Monitoring Station'}, ...
        'HorizontalAlignment', 'center', ...
        'VerticalAlignment', 'middle', ...
        'FontSize', 20, ...
        'FontWeight', 'bold', ...
        'LineStyle', 'none');
    
  31. export_fig
  32. otpath=fullfile('2Num2025');
    export_fig(otpath, '-png', '-painters', '-r300');
    pause(3);
    close all;
    

Tuesday, June 14, 2016

Matlab: Image Data Procedure

[1] 特定目录下,全部影像文件对应像元DN数值:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
% Created by LI Xu
% Version 1.0
% June 14, 2016

% Description:
% Recognize pixels

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/


function dns=GetDirDN(TarDir, index)

    dns=[];
    files=dir(fullfile(TarDir, '*.tif'));
    % Loop
    for ii=1:length(files)
        filename=files(ii).name;
        filepath=fullfile(TarDir, filename);
        image=imread(filepath);
        DN=image(index);
        dns=AddData(dns, DN);
    end


end

Friday, March 11, 2016

Matlab: MODIS Products

Introduction

这里整理一些MODIS产品可以通用的代码。
月值数据从文件名称返回年月信息:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
% Created by LI Xu
% Version 1.0
% March 11, 2016

% Description:
% Recognize the sample time in YYYYMM format

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

function yymm=ReYYMM(filename)

    yymm=strsplit(filename, '.');
    yymm=yymm{2};
    yymm(1)=[];
    yy=yymm(1:4);
    yy=str2num(yy);
    mm=yymm(end-2:end);
    mm=str2num(mm);
    
    for ii=1:12
        dd=eomday(yy, ii);
        mm=mm-dd;
        if mm<0
            break;
        end
        
    end
    yymm=yy*100+ii;

end
日序数据从文件名称返回年月日信息:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
% Created by LI Xu
% Version 1.0
% Feb. 05, 2025


% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

clear;
clc;

timebegin=tic;
cur_data=date;
cur_time=fix(clock);
str1=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time Begin: ');
fprintf(str1);
fprintf('\n');

% Source Directory
SouDir='input';
% Destination Directory
DesDir='output';

% All Files
files=dir(fullfile(SouDir, '*.tif'));

% Loop
for ii=1:numel(files)
    filepath=fullfile(SouDir, files(ii).name);
    strs=strsplit(files(ii).name, '.');

    ymlabel=strs{1};
    ymlabel(1)=[];

    ymlabel=GenYYMMDD(ymlabel);
    strs{1}=ymlabel;

    newname=strjoin(strs, '.');
    otpath=fullfile(DesDir, newname);

    % Move file
    movefile(filepath, otpath);

    disp(['[', num2str(ii), '/', num2str(numel(files)), ']~', otpath]);



end


fprintf('Time Begin: ');
fprintf(str1);
fprintf('\n');
cur_data=date;
cur_time=fix(clock);
str2=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time End: ');
disp(str2);
timespan=toc(timebegin);
fprintf('Time Span: %.4f s\n', timespan);



disp('****************************************************');

function  output=GenYYMMDD(input)
    output=[];
    yyyy=input(1:4);
    doy=input(5:7);
    [mm, dd] = ddd2mmdd(str2num(yyyy), str2num(doy));

    output=str2num(yyyy)*10000+mm*100+dd;

    output=num2str(output);

end


function [mm,dd] = ddd2mmdd(year, ddd) 
    v = datevec(datenum(year, ones(size(year)), ddd));
    mm = v(:,2); dd = v(:,3);
end

Wednesday, March 9, 2016

Code: Archiver Code

博士论文数据

[9] 提取生态安全指数(年度归纳).
[10] 归纳评价生态安全指数贡献率(全局纵向).
[11] 归纳权重识别(全局纵向).
[12] 重心识别(年度、归纳).
[15] 归纳评价得分之子系统分量占比(全局、纵向).

25指标

[2] 年度指标分量贡献提取(全局纵向).
[3] 栅格年度指标分量(全局纵向).
[4] 栅格多年指标分量(全局纵向).
[5] 多年指标分量贡献提取(全局纵向).
[6] 逐年准则层指标分量贡献(全局纵向).
[7] 多年准则层指标分量贡献(全局纵向).
[17] 等级比重6等级(逐年多年).
[21] 移动平均三子系统指数分量(全局纵向).
[22] 移动平均指标层指数分量(全局纵向).
[30] 敏感度系数(逐年移动平均).

Thursday, November 19, 2015

Tool: Tutorials Point

Summary

Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms.
Fig. 1
在Fig. 1当中的搜索框框中键入语言类型,如Matlab,随后选择Execute Matlab/Octave Online,跳跃至新页面就可以输入代码并在线测试代码,见Fig. 2。
Fig. 2
除Matlab之外,该网站还包括Python、C#、Java等语言编译器,在线编译器的缺点也很明显,速度较慢,因而比较适合临时编译代码。

References

Thursday, November 12, 2015

Code: Miscellaneous

1.[Python]查找特定后缀名称文件并返回完整路径;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#Reference
#https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-with-python/3964691#3964691
def GetFileListExt(SouDir, FlagStr):
    import glob, os
    FileList=[]
    os.chdir(SouDir)
    filter_str='*'+FlagStr
    #print filter_str
    for filepath in glob.glob(filter_str):
        FileList.append(os.path.join(SouDir, filepath))
    return FileList
2.[Arcpy]若参数是Optional,在不确定情况下可用"#"表示;
3.[Arcpy]获取shapefile文件的全部属性名称;
1
2
3
4
5
6
# Reference
# http://gis.stackexchange.com/questions/140653/in-arcpy-how-to-call-specific-columns-of-attribute-table
fieldlist=arcpy.ListFields(filepath)
    print filepath
    for field in fieldlist:
        print field.name
1
2
3
% Reference
% http://blog.sciencenet.cn/blog-1148346-842075.html
geotiffwrite('m2.tif', image, geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
7.[IDL]file_search函数使用方法总结:1, 2;
1
set(gcf,'outerposition',get(0,'screensize'));
10.[Matlab]输出图片的强大Toolbox,用法说明参考在线文档:export_fig;以如下代码保存图片,避免意外:
1
export_fig('exportfig_painters.png', '-png', '-painters', '-r300');
当图片包含中文字符时请参考此段代码:
1
export_fig([name,'.png'], '-png', '-r400','-q300');
11.[Matlab]栅格数据线性斜率参考代码;
12.[Matlab]若干.mat文件中的变量逐一以变量名另存为.xlsx文件:mat2xls.m;
13.[Python]获取目录下的包含一定字符的文件路径:(不能肯定指向后缀名.extension)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# -*- coding: utf-8 -*-  
#~ #----------------------------------------------------------------------  
#~module:wlab  
#~Filename:wgetfilelist.py  
#~Function :  
#~def IsSubString(SubStrList,Str)  
#~def GetFileList(FindPath,FlagStr=[]):  
#~功能:读取指定目录下特定类型的文件名列表  
#~Data: 2013-08-08,星期四  
#~Author:吴徐平  
#~Email:wxp07@qq.com  
#~http://blog.csdn.net/rumswell/article/details/9818001
#~ #----------------------------------------------------------------------  
#~ #----------------------------------------------------------------------  
def IsSubString(SubStrList,Str):  
    ''''' 
    #判断字符串Str是否包含序列SubStrList中的每一个子字符串 
    #>>>SubStrList=['F','EMS','txt'] 
    #>>>Str='F06925EMS91.txt' 
    #>>>IsSubString(SubStrList,Str)#return True (or False) 
    '''  
    flag=True  
    for substr in SubStrList:  
        if not(substr in Str):  
            flag=False  
  
    return flag  
#~ #----------------------------------------------------------------------  
def GetFileList(FindPath,FlagStr=[]):  
    ''''' 
    #获取目录中指定的文件名 
    #>>>FlagStr=['F','EMS','txt'] #要求文件名称中包含这些字符 
    #>>>FileList=GetFileList(FindPath,FlagStr) # 
    '''  
    import os  
    FileList=[]  
    FileNames=os.listdir(FindPath)  
    if (len(FileNames)>0):  
       for fn in FileNames:  
           if (len(FlagStr)>0):  
               #返回指定类型的文件名  
               if (IsSubString(FlagStr,fn)):  
                   fullfilename=os.path.join(FindPath,fn)  
                   FileList.append(fullfilename)  
           else:  
               #默认直接返回所有文件名  
               fullfilename=os.path.join(FindPath,fn)  
               FileList.append(fullfilename)  
  
    #对文件名排序  
    if (len(FileList)>0):  
        FileList.sort()  
  
    return FileList  
15.[Software]ANUSPLIN V4.36;
17.[Python]Access Xls data by row:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#~#------------------------------------------------------------------
def GetXlsRows(xlspath, indexes, records, offset):
    import xlrd
    workbook=xlrd.open_workbook(xlspath)
    # loop for every single sheet
    import math
    for sheetno in indexes:
        #print sheetno
        try:
            worksheet=workbook.sheet_by_index(sheetno)
            records=GetRecords(worksheet, offset, records)
        except:
            continue
    return records
#~#------------------------------------------------------------------
def GetRecords(worksheet, offset, records):
    for i, row in enumerate(range(worksheet.nrows)):
        if i <offset:
            continue
        r=[]    
        for j, col in enumerate(range(worksheet.ncols)):
            r.append(worksheet.cell_value(i, j))
        records.append(r)
    return records
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
% Created by LI Xu
% Version 1.0
% November 23, 2015

% Description:
% Check out the current Matlab lincense Info

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Reference
% http://stackoverflow.com/questions/2060382/how-would-one-check-for-installed-matlab-toolboxes-in-a-script-function

clear;
clc;

% Display toolbox version info
ver
disp('**************************************************');
disp('Display a list of licenses currently being used.');
license('inuse')
disp('**************************************************');
disp('Check out a license for all the available toolboxes.');
featureStr = {'Aerospace_Blockset'; ...
              'Aerospace_Toolbox'; ...
              'Bioinformatics_Toolbox'; ...
              'Communication_Blocks'; ...
              'Communication_Toolbox'; ...
              'Compiler'; ...
              'Control_Toolbox'; ...
              'Curve_Fitting_Toolbox'; ...
              'Data_Acq_Toolbox'; ...
              'Database_Toolbox'; ...
              'Datafeed_Toolbox'; ...
              'Dial_and_Gauge_Blocks'; ...
              'Distrib_Computing_Toolbox'; ...
              'Econometrics_Toolbox'; ...
              'EDA_Simulator_Link_DS'; ...
              'Embedded_Target_c166'; ...
              'Embedded_Target_c2000'; ...
              'Embedded_Target_c6000'; ...
              'Embedded_Target_MPC555'; ...
              'Excel_Link'; ...
              'Filter_Design_HDL_Coder'; ...
              'Filter_Design_Toolbox'; ...
              'Fin_Derivatives_Toolbox'; ...
              'Financial_Toolbox'; ...
              'Fixed_Income_Toolbox'; ...
              'Fixed_Point_Toolbox'; ...
              'Fixed-Point_Blocks'; ...
              'Fuzzy_Toolbox'; ...
              'GADS_Toolbox'; ...
              'IDE_Link_MU'; ...
              'Identification_Toolbox'; ...
              'Image_Acquisition_Toolbox'; ...
              'Image_Toolbox'; ...
              'Instr_Control_Toolbox'; ...
              'Link_for_Incisive'; ...
              'Link_for_ModelSim'; ...
              'Link_for_Tasking'; ...
              'Link_for_VisualDSP'; ...
              'MAP_Toolbox'; ...
              'MATLAB'; ...
              'MATLAB_Builder_for_dot_Net'; ...
              'MATLAB_Builder_for_Java'; ...
              'MATLAB_Distrib_Comp_Engine'; ...
              'MATLAB_Excel_Builder'; ...
              'MATLAB_Link_for_CCS'; ...
              'MATLAB_Report_Gen'; ...
              'MBC_Toolbox'; ...
              'MPC_Toolbox'; ...
              'NCD_Toolbox'; ...
              'Neural_Network_Toolbox'; ...
              'OPC_Toolbox'; ...
              'Optimization_Toolbox'; ...
              'PDE_Toolbox'; ...
              'Power_System_Blocks'; ...
              'Real-Time_Win_Target'; ...
              'Real-Time_Workshop'; ...
              'RF_Blockset'; ...
              'RF_Toolbox'; ...
              'Robust_Toolbox'; ...
              'RTW_Embedded_Coder'; ...
              'Signal_Blocks'; ...
              'Signal_Toolbox'; ...
              'SimBiology'; ...
              'SimDriveline'; ...
              'SimElectronics'; ...
              'SimEvents'; ...
              'SimHydraulics'; ...
              'SimMechanics'; ...
              'Simscape'; ...
              'SIMULINK'; ...
              'Simulink_Control_Design'; ...
              'Simulink_Design_Verifier'; ...
              'Simulink_HDL_Coder'; ...
              'Simulink_Param_Estimation'; ...
              'SIMULINK_Report_Gen'; ...
              'SL_Verification_Validation'; ...
              'Spline_Toolbox'; ...
              'Stateflow'; ...
              'Stateflow_Coder'; ...
              'Statistics_Toolbox'; ...
              'Symbolic_Toolbox'; ...
              'SystemTest'; ...
              'Video_and_Image_Blockset'; ...
              'Virtual_Reality_Toolbox'; ...
              'Wavelet_Toolbox'; ...
              'XPC_Embedded_Option'; ...
              'XPC_Target'};
index = cellfun(@(f) license('test',f),featureStr);
availableFeatures = featureStr(logical(index));
index = cellfun(@(f) license('checkout',f),availableFeatures);
checkedOutFeatures = availableFeatures(logical(index))
fprintf('Total: %d.\n', length(checkedOutFeatures));
disp('**************************************************');
19.[python]文件名称包含特定序列字符:
1
2
3
4
5
6
7
8
def GetFileSubStr(SouDir, flagstr):
    import os, glob
    allfiles=os.listdir(SouDir)
    filepath=[]
    for file in allfiles:
        if flagstr in file:
            filepath=os.path.join(SouDir, file)
            return filepath
20.[Matlab] Change language for Matlab desktop
21.[Matlab]函数Text指定中文字体须以其英文名称为准,如黑体是SimHei,此时才为有效:
1
input=['\fontname{Arial}(', char(96+ii), ') \fontname{SimHei}', names{ii}];
  • 黑体:SimHei
  • 宋体:SimSun
  • 新宋体:NSimSun
  • 仿宋:FangSong
  • 楷体:KaiTi
  • 仿宋_GB2312:FangSong_GB2312
  • 楷体_GB2312:KaiTi_GB2312
  • 微软雅黑体:Microsoft YaHei
23.[Matlab]Plot添加字符
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
% Created by LI Xu
% Version 1.0
% November 27, 2015

% Description:
% Insert Text on the plot figure

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Example
% instr={str1, str2, str3};
% instratts.font='Arial';
% instratts.xsclae=0.2;
% instratts.yscale=0.3;
% instratts.fontsize=12;
% instratts.interval=0.1;
% PlotAddText(gca, instr, instratts);

function PlotAddText(handle, instr, instratts)
    % Get xlim ylim
    xlim=get(handle, 'xlim');
    ylim=get(handle, 'ylim');
    
    fontsize=instratts.fontsize;
    if fontsize<1
        fontsize=(ylim(2)-ylim(1))*fontsize;
    end
    
    % Loop
    for ii=1:length(instr)
        strVal=instr{ii};
        x=(xlim(2)-xlim(1))*instratts.xscale+xlim(1);
        y=(ylim(2)-ylim(1))*instratts.yscale+ylim(1);
        y=y-(ylim(2)-ylim(1))*instratts.interval*(ii-1);
        text(x, y, strVal, 'fontname', instratts.font, ...
            'fontsize', fontsize);
    end
end

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
% Created by LI Xu
% Version 1.0
% November 27, 2015

% Description:
% Insert Text on the plot figure

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

% Modification
% Add color property
% Version 1.1
% May 11, 2015

% Example
% instr={str1, str2, str3};
% instratts.font='Arial';
% instratts.xscale=0.2;
% instratts.yscale=0.3;
% instratts.fontsize=12;
% instratts.interval=0.1;
% instratts.color=[0, 0, 0];
% PlotAddText(gca, instr, instratts);

function PlotAddText(handle, instr, instratts)
    % Get xlim ylim
    xlim=get(handle, 'xlim');
    ylim=get(handle, 'ylim');
    
    fontsize=instratts.fontsize;
    if fontsize<1
        fontsize=(ylim(2)-ylim(1))*fontsize;
    end
    
    % Loop
    for ii=1:length(instr)
        strVal=instr{ii};
        x=(xlim(2)-xlim(1))*instratts.xscale+xlim(1);
        y=(ylim(2)-ylim(1))*instratts.yscale+ylim(1);
        y=y-(ylim(2)-ylim(1))*instratts.interval*(ii-1);
        text(x, y, strVal, 'fontname', instratts.font, ...
            'fontsize', fontsize, 'color', instratts.color./255);
    end
end
24.[Matlab]插入°C,此时Matlab当前编码类型应是'Windows-1252'
25.[Matlab]Matlab显示点乘(dot product)符号,按照Tex语言
1
2
data = double(py.array.array('d',py.numpy.nditer(x))); %d is for double, see link below on types
data = reshape(data,[4 4])'; %Could incorporate x.shape here ...
28.[Matlab]返回指定目录下特定文件的一定位置的数值(DN)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
% Created by LI Xu
% Version 1.0
% January 26, 2016

% Description
% Retrieve the DNs of multiple files

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

function data=RetDNs(SouDir, files, index)
    data=[];
    % Loop
    for ii=1:length(files)
        filename=files(ii).name;
        filepath=fullfile(SouDir, filename);
        file=imread(filepath);
        DN=file(index);
        data=AddData(data, DN);
    end

end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function    [ st, msg ] = cmd_rmdir( folderspec )       
%   cmd_rmdir removes a directory and its contents 
%   
%   Removes all directories and files in the specified directory in
%   addition to the directory itself.  Used to remove a directory tree.
%   See also: xtests\generic_utilies_test.m      
    narginchk( 1, 1 )
    dos_cmd = sprintf( 'rmdir /S /Q "%s"', folderspec ); 
    [ st, msg ] = system( dos_cmd );
end
30.[Matlab]过滤像元,小于定值者重设为定值
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
% Created by LI Xu
% Version 1.0
% Febuary 2, 2016

% Description
% Replace values with new

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

clear;
clc;

% Source Directory
SouDir='./input';
% Destination Directory
DesDir='./output';

% All Files
files=dir(fullfile(SouDir, '*.tif'));
keyval=0;

for ii=1:length(files)
    filename=files(ii).name;
    inpath=fullfile(SouDir, filename);
    [image, geo]=geotiffread(inpath);
    info=geotiffinfo(inpath);
    index=find(image<keyval);
    if ~isempty(index)
        image(index)=keyval;
    end
    
    % Export
    otpath=fullfile(DesDir, filename);
    geotiffwrite(otpath, image, geo, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
    disp([num2str(ii), ': ', filename]);

end

disp('*********************************************');
31.[Matlab]修改bar颜色
1
2
3
4
5
6
7
8
9
function ChangeColor(handle, RGBs)
    color=[];
    for ii=1:size(RGBs)
        rgb=RGBs(ii, :);
        color=[color; {rgb./255}];        
    end
    set(handle, {'FaceColor'}, color);

end
32.[Matlab]乘号:‘\times’;减号:‘char(8722)’;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
% Created by LI Xu
% Version 1.0
% April 10, 2016

% Description:
% Convert Lat/Long in deg/min/sec format
% to demical degree

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/


clear;
clc;

% XLS
xlspath='input.xlsx';
[rawdata, labels, ~]=xlsread(xlspath);
labels(1:2, :)=[];
labels(:, 2:end)=[];

lat=rawdata(:, 1:3);
otlat=lat(:, 1)+lat(:, 2)./60+lat(:, 3)./3600;
long=rawdata(:, 4:end);
otlong=long(:, 1)+long(:, 2)./60+long(:, 3)./3600;

otdata=[otlat, otlong];
otdata=[labels, num2cell(otdata)];

disp('*****************************************');
34.[Matlab]中文显示不正常,可以使用如下代码尝试之.
feature('DefaultCharacterSet', 'UTF8');
35.[Matlab]temll元胞向量,每个元胞含有相同大小的元胞数组,以下可以将子元胞数组打开并规则输出
newcon=vertcat(temll{:});
36.[Matlab]tight_subplot
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
% Plot
Nh=3;
Nw=1;
gap=0.018;
marg_h=0.1;
marg_w=0.1;
figure;
ha = tight_subplot(Nh, Nw, gap, marg_h, marg_w);
axes(ha(1));
axes(ha(2));
axes(ha(3));