Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts

SCRIPT FILES

Posted by Admin On Monday, July 22, 2013 0 comments
A script is a sequence of ordinary statements and functions used at the command prompt level. A script is invoked the command prompt level by typing the file-name or by using the pull down menu. Scripts can also invoke other scripts.
The commands in the Command Window cannot be saved and executed again. Also, the Command Window is not interactive. To overcome these difficulties, the procedure is first to create a file with a list of commands, save it and then run the file. In this way, the commands contained are executed in the order they are listed when the file is run. In addition, as the need arises, one can change or modify the commands in the file; the file can be saved and run again. The files that are used in this fashion are known as script files. Thus, a script file is a text file that contains a sequence of MATLAB commands. Script file can be edited (corrected and/or changed) and executed many times.

Creating and Saving a Script File
Any text editor can be used to create script files. In MATLAB, script files are created and edited in the Editor/ Debugger Window. This window can be opened from the Command Window. From the
Command Window, select File, New and then M-file. Once the window is open, the commands of the script file are typed line by line. The commands can also be typed in any text editor or word processor program and then copied and pasted in the Editor/Debugger Window. The second type of M-files is the function file. Function file enables the user to extend the basic library functions by adding ones own computational procedures. Function M-files are expected to return one or more results. Script files and function files may include reference to other MATLAB toolbox routines.
MATLAB function file begins with a header statement of the form:
function (name of result or results) = name (argument list)

Before a script file can be executed it must be saved. All script files must be saved with the extension “.m”. MATLAB refers to them as M-files. When using MATLAB M-files editor, the files will automatically be saved with a “.m” extension. If any other text editor is used, the file must be saved with the “.m” extension, or MATLAB will not be able to find and run the script file. This is done by choosing Save As... from the File menu, selecting a location, and entering a name for the file. The names of user defined variables, predefined variables, MATLAB commands or functions should not be used to name script files.

Running a Script File
A script file can be executed either by typing its name in the Command Window and then pressing the Enter key, directly from the Editor Window by clicking on the Run icon. The file is assumed to be in the current directory, or in the search path.
Input to a Script File
There are three ways of assigning a value to a variable in a script file.
1. The variable is defined and assigned value in the script file.
2. The variable is defined and assigned value in the Command Window.
3. The variable is defined in the script file, but a specified value is entered in the Command Window when the script file is executed.

References:
1. 'Matlab An Introduction with Applications', Rao V. Dukkipati
2. 'Matlab Ders Notları', Hasan Korkmaz
3. http://mathworks.com 

If you have any question or need some help, leave a comment below.
READ MORE

Random Walk using Matlab

Posted by Admin On Thursday, February 14, 2013 0 comments

x=0;
y=0;
xv=x;
yv=y;

while (abs(x)<10 && abs(y)<10)
    d=randi(4);
    switch d
        case 1       %N=1
            y=y+1;
        case 2       %S=2
            y=y-1;
        case 3       %E=3
            x=x+1;
        otherwise
            x=x-1;
    end

    xv(end+1)=x;
    yv(end+1)=y;
end

figure
axis([-10,10,-10,10])
title(['Random walk tooks ',num2str(length(xv)),' steps']);
hold on
comet(xv,yv);
hold off
READ MORE

Slide Show using Matlab

Posted by Admin On 0 comments




figure
n=1;

while n<=12
    membrane(n);
    shading interp;
    title(['Eigenfunction # ', num2str(n)]);
    colormap(spring);
    pause(1.0);
    n=n+1;
end
READ MORE

Initial Arrangements in Matlab

Posted by Admin On 0 comments



str2=input('','s');
if strmatch('do the arrangements\n',str2)

    disp('Yes Sir')
end


cd 'path'
winopen('path');
fprintf('Welcome to Matlab, Mr. 'name'\nCurrent Directory is rearranged, and the mlbe file is opened.\n');

str1=input('','s');
if strmatch('thanks',str1)
    disp('You are Welcome');
    clear;
end

READ MORE

A Traveling Wave by Making an Animation in MATLAB

Posted by Admin On Monday, February 11, 2013 0 comments

clc %clears the command window
clear %clears variables
%Variables:
%Eo wave amplitude (V/m)
%f frequency (Hz)
%omega angular frequency (rad/s)
%t time snapshot
%c speed of light
%z position
%E Electric Field Intensity
%B phase constant (1/m)
%phi phase constant (s)
%phir phase constant (radians)
%lambda wavelength
(m)
%Initial Values of Variables:
f=1000;
phi=0;
c=2.998e8;
lambda=c/f;
t=1;
phir=phi*pi/180;
Eo=1;
B=2*pi/lambda;
omega=2*pi*f;
z=0:4*lambda/100:4*lambda;
E=Eo*cos(omega*t-B*z+phir);
plot(z,E)
axis([0 4*lambda -2*Eo 2*Eo])
grid
xlabel('z(m)')
ylabel('E(V/m)')
pause
t=0:1/(40*f):1/f;
for n=1:40;
E=Eo*cos(omega*t(n)-B*z+phir);
plot(z,E)
axis([0 4*lambda -2*Eo 2*Eo])
grid
title('General Wave Equation');
xlabel('z(m)');
ylabel('E(V/m)');
M(:,1)=getframe;
end


After that I run it from the command window. I give three figures these are in different time to
see properly the wave is travelling.






READ MORE

Modelling a Digital Communication System using Matlab

Posted by Admin On Thursday, February 7, 2013 0 comments

A digital telephone converts an analog signal(our voice) to a digital signal before transmission. While the analog signal takes on real number values, the digital signal takes on only a finite set of integer
values. We can model these implementation effects and save memory by storing the digital as
an integer data type rather than as type double. We did this by using the script in the
following.

%% ====== Sources ======
% Load sampled (discretized time) analog sources
% with double values between -1 and +1.
load phonecalls
% See and hear both sources together.
% Note source clipping at -1 and +1.
plot(source1,'r')
hold on
plot(source2,'b')
ylabel('DOUBLE Values')
title('{\bf Analog Sources}')
legend('Source 1','Source 2')
soundsc([source1,source2],Fs) % Stereo
pause(4)
%% ====== Source coding (quantization) ======
% Digital signals (discretized values) with scaled
% and quantized int8 values between -128 and 127.
sig1 = int8(128*source1);
sig2 = int8(128*source2);
% See and hear both signals together.
% Clipped values at -1 and +1 in the sources
% saturate in the signals at -128 and 127.
figure
plot(sig1,'r.')
hold on
plot(sig2,'b.')
ylabel('INT8 Values')
title('{\bf Digital Signals}')
legend('Signal 1','Signal 2')
soundsc([double(sig1),double(sig2)],Fs) % Stereo
------
As you see from the script I plotted the analog sources and the digital signals seperately. The
plot are shown in Figures. Any other necessary explanations is in the comments in the
script.
I want to speak about some functions and commands these are we used in the script above.
load: load workspace variables from disk.
soundsc: Scale data and play as sound.
pause: Halt execution temporarily.
int8: Stored integer value of fi object as built-in int8

                                                     Analog Sources which is like our voice



                                            Digital Signals represent data in Analog Signals




READ MORE

Yapılar(Structures)

Posted by Admin On Monday, August 27, 2012 0 comments
Yapılar hücre dizileri gibi birbiriyle benzerliği olmayan bilgileri bir araya getirmek için kullanılır. Bilgiler tek bir değişkende toplanır yani yapıda.(structure) Şöyle tanımlanır:

S.fieldname=value;   S:yapının adıdır, fieldname:alt daldaki etikettir, value: alt daldaki bu etiketin değeridir.

Eğer field name i bir değişkende taşımak ve bunu bir structure da kullanmak istiyorsak şöyle yapmamız gerekir:

a='fieldname';
S.(a)=value;

Ayrıca, structure bir fonksiyon için input olarak kullanılabilir.



READ MORE

Yapı Dizilerinde İndeksleme(Indexing into Structure Arrays)

Posted by Admin On 0 comments
İndeksleme normal parantezlerle veya direk field name ile yapılabilir. Örnekler:
S(2)
S.a
S(3).a
S([1,5])
S(1:4).a
y={S(1:4).a}

READ MORE

Yapı Dizileri(Structure Arrays)

Posted by Admin On Sunday, August 26, 2012 0 comments
Yapı dizileri herhangi bir boyutta olabilirler. Elemanlara parantezle erişilebilir. Örneğin:

S(1).a=4;
S(2).a=5;
S(1).b=46;
S(2).c=ones(3);
S(3).a=magic(2);
S(4).b='world';

S


S =

1x4 struct array with fields:
    a
    b
    c

READ MORE

Hücre Dizileri(Cell Arrays)

Posted by Admin On Friday, August 24, 2012 0 comments
Hücre dizileri herhangi bir tip veya boyuttaki dizileri birleştirmek için kullanılabilir. Teknik olarak bir hücre dizisindeki hücreleri birer işaretçi(pointers) gibi düşünebiliriz.
Hücre dizileri için hafızada ön ayırma yapabiliriz. Şöyle ki:
x=cell(m,n);
komutu mXn boyutunda boş bir hücre dizisi oluşturur.
Hücre dizilerini birleştirmek için süslü parantez { } ya da köşeli parantez [ ] kullanabiliriz.
Ayrıca süslü parantezler { } hücrenin içeriğine erişimimizi sağlarken normal parantezler ( ) hücrenin kendisine ulaşmamızı sağlar.

READ MORE

Tam Sayı Dizileri(Integer Arrays)

Posted by Admin On 0 comments
Matlabta dört tane işaretli ve dört tane işaretsiz olmak üzere toplamda sekiz tane tam sayı veri çeşidi vardır. Bunlar:
  • int8, int16, int32, int64
  • uint8, uint16, uint32, uint64
Örneğin:
               B=zeros(m,n,'int8');
B nin elemanları hafızada int8 tipine göre kaydedilecektir.

READ MORE

Matlab Veri Çeşitleri(Matlab Data Types)

Posted by Admin On 0 comments
Matlab'ta 15 tane temel veri çeşidi vardır. Bunların başlıcaları:

  • logical
  • char
  • numeric(single,double)
  • cell
  • structure
  • function handle
  • user class
READ MORE

Hafıza Ön Ayırması(Preallocation of Memory)

Posted by Admin On 0 comments

Bazen yazdığımız scriptlerde matris ya da dizi oluştururken baştan bunların boyutları tam olarak belli olmayabilir. Bu Matlab'in işi daha yavaş yapmasına neden olur. Ancak daha işlemin başında kodumuza şöyle bir satır eklersek:
A=zeros(m,n);
bu Matlab'in işin başında A matrisi için hafızada yer ayırtmasına ve geri kalan işlemleri ve değişiklikleri daha hızlı yapmasına yardımcı olur. Yani kodumuzun performansını bilinçli olarak artırmış oluruz.
READ MORE

Kodun Performansı(Code Performance)

Posted by Admin On 0 comments

Matlab'ta belirlenmiş altı tane görev vardır. Bunların doc bench yazarak görebiliriz. bench(n) komutu bize bu görevlerin farklı bilgisayar ve işletim sistemlerinde ne kadar zamanda yapılabileceğinin karşılaştırmalı
grafiklerini verir.
Kodumuzun ne kadar zamanda çalıştırıldığını bulmak için tic ve toc komutlarını kullanırız. Şöyle ki:
tic; code_name; toc;
komutu kodumuzu çalıştırır ve geçen zamanı command window da gösterir.
Matlab Profiler bize bu konuda daha ayrıntılı bilgi verir. Desktop sekmesinden Profiler seçilerek profiler ı açabiliriz ya da profile viewer komutu ile açabiliriz.

READ MORE

Editörde Kod Analizi

Posted by Admin On 0 comments
Matlab editörü kod analizi yapan bir araca sahiptir. Biz kodlarımızı yazarken yazım hataları için kontrolü yapar bu araç. Hatalı kısımları veya uyarı ya da tavsiye vermek istediği kısımların altını çizer. Mouse ile altı çizili kısmın üstüne gidersek bize hatayı,uyarıyı ya da tavsiyesini gösterir. Ek olarak, kodda bazı belirli problemler turuncu ya da kırmızı renkte altı çizili çizgilerle görünür. Renkler ve anlamları şöyledir:

Yeşil         Kodda yazım hatası yok demektir.
Turuncu   Beklenmeyen sonuçlar getirebilecek bir potansiyel var ya da performans açısından yetersiz bir ifade.
Kırmızı     Yazım hatası var anlamındadır.


READ MORE

The Matlab Path

Posted by Admin On Thursday, August 23, 2012 0 comments
Matlab path ayarlarını pathtool komutunu command window a yazıp açılan Set Path penceresinden ayarlayabiliriz. Ayrıca  Set Path penceresini file sekmesinden de açabiliriz. path komutu bize kayıtlı bütün path leri verir. which komutu dosyanın ya da fonksiyonun yerini path ismi ile birlikte verir. (which file_name or function_name)
Eğer which komutu all opsiyonu ile birlikte kullanılırsa şöyle ki;
which function_name or file_name -all
Aynı isimdeki bütün dosyaların yerlerini pathleriyle birlikte öncelik sırasına göre verir.
*Mini Bilgi:matlabroot komutu matlab bilgisayarınızda hangi klasöre kurulmuşsa o klasörün path ini verir.
                                                                                                                                    
                                                                                                                                                  
READ MORE

Alt Fonksiyonlar(Subfunctions)

Posted by Admin On 0 comments

Bir fonksiyon dosyası birden fazla fonksiyona ait declaration ve tanımlamaları içerebilir. Ancak bunlardan sadece en üstteki yani primary fonksiyon workspace ten çağrılabilir. Diğerleri sadece fonksiyon dosyasının içinde çağrılabilir.

READ MORE

Fonksiyonların Çalışma Alanları

Posted by Admin On 0 comments
Bir Fonksiyon çağrıldığı zaman ona ait bütün değişkenler ana workspace ten ayrı olarak başka bir workspace te tanımlanır kaydedilir. Fonksiyonun çalışması bittiği zaman bu özel-ayrı workspaceteki değişkenler silinir.
READ MORE



F=Vandermonde matrix, c=katsayılar, M=data, fitM=fitlenmiş data(yeni modelimiz), resid=hata, mse=mean square error ,N=datanın eleman sayısı olsun.
Önce Vandermonde matrisi istenildiği gibi üretilir boyutu fitlenicek datanın boyutuna uygun olarak. Daha sonra F*c=M denklemi backslash yöntemi kullanılarak çözülür(c=F\M). fitM=F*c den bulunur. Diğer değerler de aşağıda belirtildiği gibi bulunur:
resid=fitM-M;
mse=resid'*resid/N;
READ MORE

Otomatikliği Artırmak-Fonksiyon Yaratmak-Fonksiyon Çağırmak

Posted by Admin On 0 comments

Otomatikliği Arttırmak

Kendi yazdığımız veya önceden yazılmış hazır scriptleri veya fonksiyonları kullanarak otomatikliği arttırabiliriz.

Fonksiyon Yaratmak

Fonksiyon dosyaları her zaman bir function declaration ile başlar. Şöyle ki:
function [out1,out2,...]=function_name(in1,in2,...)

bu komut satırı her fonksiyon dosyasının başında mutlaka bulunmalıdır.

Bir Fonksiyonu Çağırmak

[out1,out2,...]=function_name(in1,in2,...)
ile çağrılır.

READ MORE