در این مقاله از مرکز درس، در راستای آموزش های نرم افزار متلب می خواهیم یک سری نکات عمومی از بخش برنامه نویسی در این نرم افزار را به شما آموزش بدهیم. برنامه نویسی در متلب یکی از مهم ترین بخش های کار با این نرم افزار می باشد و تعریف متغیر ها و فرمول ها و خیلی از کارهای دیگر در آن به کمک برنامه نویسی انجام می شود. پس با ما همراه باشید :
تیپ عمومی
- تعریف یک بردار
x( 3:5 ) = [];
- معکوس کردن بردار
x = x(end:-1:1);
- محاسبه زمان اجرای فراخوانی یک تابع
tic; fft(rand(500)); disp( [‘it takes ‘ num2str(toc) ‘s.’])
- اختصاص دیتا به یک آرایه
% guess which one is the fastest ?
tic; NaN*ones(2000,2000); toc;
tic; repmat(NaN,2000,2000); toc;
- تبدیل یک آرایه به یک بردار
x = x(:);
- محاسبه مقدار بیشینه یک آرایه.
m = max(x(:));
- دسترسی به ماتریس از لیست موجودی ها. در اینجا ما داریم :
I = [I1; I2] and y(i) = M( I1(i), I2(i) )
J = sub2ind(size(M), I(1,:),I(2,:) );
y = M(J);
- ایجاد یک تابع که آرگومان اختیاری از ورودی می گیرد.
function y = f(x,options function y = f(x,options)
% parse the struct
if nargin
options.null = 0; % force creation of options
end
if isfield(options, ‘a’)
options.a = 1; % default value
end
a = options.a;
if isfield(options, ‘b’)
options.b = 1; % default value
end
b = options.b;
% Here the body of the function …
- ایجاد یک نوار حاشیه گرافیکی.
n = 100;
h = waitbar(0,’Waiting …’);
for i=1:n
waitbar(i/n);
% here perform some stuff
end
close(h);
- چگونه کاراکتر ها را برای چند بار تکرار و دوبل کنیم.
str = char( zeros(n,1)+’*’ );
- نمایش یک رشته در خروجی
fprintf(‘Some Text’);
- اختصاص مقدار خانه ind ارایه به ind
ind = num2cell(ind);
x( ind: ) = v;
- شکل فعلی را به عنوان یک تصویر با فرمت فایل EPS ذخیره کنید
saveas(gcf, str, ‘png’);
- تیک های یک ترسیم را حذف کنید
set(gca, ‘XTick’, []);
set(gca, ‘YTick’, []);
- ذخیره و لود کردن یک تصویر
saveas(gcf, ‘my image’, ‘png’); % save
M = double( imread( ‘my image.png’ ) ); % load
- ذخیره و لود یک ماتریس بصورت باینری
[n,p] = size(M); % saving
str = ‘my file’; % name of the file
fid = fopen(str,’wb’);
if fid
error([‘error writing to file ‘, str]);
end
fwrite(fid,M,’double’);
fclose(fid);
% loading
fid = fopen(str,’rb’);
if fid
error([‘error reading file ‘,str]);
end
[M, cnt] = fread(fid,[n,p],’double’);
fclose(fid);
if cnt =n*p
error([‘Error reading file ‘, str]);
end
- پیدا کردن زاویه بین دو بردار
% just the angle
theta = atan2(x(2),x(1));
% if you want to compute the full polar decomposition
[theta,r] = cart2pol(x);
- تغییر نسبت اندازه یک بردار
m = min(x(:)); M = max(x(:));
x = (b-a) * (x-m)/(M-m) + a;
- تولید n نقطه پیوسته
x = 0:1/(n-1):1; % faster than linspace
- محاسبه توان دوم یک ماتریس
m = sum(x(:).ˆ۲);
- انتخاب یک بخشی از بردار
x = x(1:2:end); % useful for wavelet transform
M = M(1:2:end,1:2:end);
- محاسبه اختلاف قطر اصلی دو ماتریس
D1 = [x(2:end),x(end)];
D2 = [x(1),x(1:end-1)];
y = (D1-D2)/2;
- محاسبه اولین عدد اول قبل از n
n = 150;
P = primes(n); n = P(end);
J(I) = 1:length(I);
- بهم ریختن تصادفی یک آرایه
y = x( randperm(length(x)) );