Matlab一些简单的操作tips

作者:matrix 被围观: 2,692 次 发布时间:2019-08-12 分类:零零星星 | 无评论 »

这是一个创建于 1718 天前的主题,其中的信息可能已经有所发展或是发生改变。

由于matlab编程偏向于学术方面,对于我这种😍喜欢OOP以及普通字符串操作来说多少的不熟悉和麻烦。
遂记录。

timer定时器操作

类似于javascript的setInterval操作

myTimer = timer('Name','MyTimer',               ...
    'Period',2,                 ... % 2秒钟间隔
    'StartDelay',0,                 ...
    'TasksToExecute',inf,           ...
    'ExecutionMode','fixedSpacing', ...
    'TimerFcn',@myTimerCallback,...
    'ErrorFcn',@(~,thisEvent)exit);%  如果报错 则推出程序

start(myTimer);%启动

function myTimerCallback(hObject, eventdata)
     disp(['run time:: ', datestr(datetime('now'),'yyyy-mm-dd HH:MM:SS') ])
end

删除所有定时器:

delete(timerfindall());

手动抛异常

baseException = MException('MYFUN:BadParameter','Parameter miss');
throw(baseException);

throw函数需要传入异常类。
MException类第一个参数为msgID。必须要有冒号:,名称都可以自定义。
参考:
https://ww2.mathworks.cn/help/matlab/ref/mexception.html

字符串比较

使用strcmp函数进行字符串比较。
不同于使用双等号==,双等号会对字符串中的每个字符进行比较相等,最终返回逻辑数组logical array

if strcmp(str,'timestr')%判断字符串相等
        dis('Content is equal');
   end

多行注释

单行注释使用百分号%
多行注释使用%{...%}

%{
  ...some thing
%}

函数默认参数判断以及设置值

function rel = func(arg1,arg2)
    if exist('arg2', 'var') && ~isempty(arg2)%如果传入arg2参数 且不为空
      bla bla
    end
end

function [result] = func(format)
    if ~exist('format', 'var') %不存在默认参数
        result = '默认参数';
    else
        result = format;
    end
end

exist函数中var表示(变量)类型

https://blog.csdn.net/liuxiabing150/article/details/46519785

删除数组指定下标

list(1) = [];%删除指定的下标的元素

del_index_list = [1 2 9 18]
list(del_index_list) = [];%删除多个下标元素

检测struct结构体字段是否存在

isfield(struct('a','1'),'a1') #判断a1字段是否存在

all(isfield(struct('field1','val1'),{'a','b'}))#判断a,b字段是否都存在

参考:
https://ww2.mathworks.cn/matlabcentral/answers/260295-dynamically-name-a-struct

动态添加struct数据key名称

data = struct();
name = 'Dynamic_Name';
data.(name) = 990;

匿名函数

匿名函数最为回调的处理和调用


% 回调函数的执行 function rel = func(arg1,callback) cb = callback(data);%执行回调函数,传入data数据作为参数 if ~cb bla bla end end %回调函数作为参数来使用 func(arg1,@(data)deal(1)); func(arg1,@(data)[a=1;deal(a);]);%匿名函数执行多条语句 %普通函数作为回调函数 func(arg1,@cb); function rel = cb(data) rel = 1 end

说明:
使用@操作符
deal函数类似于java中的return操作
方括号[]最为数组操作可以防置多条语句来执行

追加保存数据到文件

now = 1583237214;
data_diff = 1;
data_uni_diff = 2;
res = [res;now,data_diff,data_uni_diff];

dlmwrite('chech_diff_time.txt',res,'-append');

-append参数表示追加处理

判断数据类型

class(123) % double
ischar('') % logic true

其他文章:
本文固定链接:https://www.hhtjim.com/matlab-some-simple-tips-to-operate.html
matrix
本文章由 matrix 于2019年08月12日发布在零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:Matlab一些简单的操作tips-HHTjim'S 部落格
关键字:

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!