星期五, 11月 17, 2006

MATLAB課堂作業: 作業七

1. Write a program to input the name, age, sex and email address of a student and store the data as a structural format.

ANS:
程式指令:

% Q7_1.m
% input the name, age, sex and email address of a student
a=input('請輸入您的姓名:','s');
if isempty(a)
a='missing';
end
b=input('請輸入您的年齡:');
if isempty(b)
b='missing';
end
c=input('請輸入您的性別:(M/F)','s');
if isempty(c)
c='missing';
end
d=input('請輸入您的郵件地址:(ex. r94428004@ntu.edu.tw)','s');
if isempty(d)
d='missing';
end
student.Name=a;
student.Age=b;
student.Sex=c;
student.Email=d


執行結果:
(1)輸入資料齊全情況下
>> Q7_1
請輸入您的姓名:Susan
請輸入您的年齡:25
請輸入您的性別:(M/F)F
請輸入您的郵件地址:(ex. r94428004@ntu.edu.tw)r94428004@ntu.edu.tw

student =

Name: 'Susan'
Age: 25
Sex: 'F'
Email: 'r94428004@ntu.edu.tw'

(2)沒有輸入資料情況下則會輸出"missing"訊息
>> Q7_1
請輸入您的姓名:Susan
請輸入您的年齡:
請輸入您的性別:(M/F)F
請輸入您的郵件地址:(ex. r94428004@ntu.edu.tw)

student =

Name: 'Susan'
Age: 'missing'
Sex: 'F'
Email: 'missing'

2. Use the "menu" and "switch" commands incorporated in a program that enables a selection of Apple, Microsoft, IBM, Acer and Asus computers.

ANS:
程式指令:
% Q7_2.m
% a selection of Apple, Microsoft, IBM, Acer and Asus computers
com=menu('請選擇您想購買的電腦廠牌:','Apple','Microsoft','IBM','Acer','Asus');
switch com
case 1
fprintf('您選擇的電腦廠牌為 Apple\n')
case 2
fprintf('您選擇的電腦廠牌為 Microsoft\n')
case 3
fprintf('您選擇的電腦廠牌為 IBM\n')
case 4
fprintf('您選擇的電腦廠牌為 Acer\n')
case 5
fprintf('您選擇的電腦廠牌為 Asus\n')
end

執行結果:
在指令窗輸入Q7_2之後會出現一選擇視窗
選擇視窗

點選Acer之後則會在指令窗出現以下訊息:
您選擇的電腦廠牌為 Acer

3. Using fprintf and fscanf commands to store a magic matrix of order 5 in a file name magic.dat, and retrieve back to a set variable.

ANS:
magic(5)的矩陣如下
>> magic(5)

ans =

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

利用fprintf指令將magic(5)內容儲存於另一個檔案magicr94428004.dat
>> m=magic(5);
>> fid=fopen('magicr94428004.dat','w');
>> fprintf(fid,'%2.0f %2.0f %2.0f %2.0f %2.0f\n',m(1,:),m(2,:),m(3,:),m(4,:),m(5,:));
>> fclose(fid);
>> type magicr94428004.dat

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

輸出檔案結果如下:
輸出檔案

利用fscanf指令將檔案內容擷取於指令窗中
>> B=fopen('magicr94428004.dat');
>> A=fscanf(B,'%d',[5 5]);
>> fclose(fid);
>> A

A =

17 23 4 10 11
24 5 6 12 18
1 7 13 19 25
8 14 20 21 2
15 16 22 3 9

>> A'

ans =

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9



4. Write a program to retrieve data from an excell sheet.

ANS:
首先先建立一個excell檔案,再將檔案內內容擷取出來

程式指令:
% Q7_4.m
F={'水果名稱' '產季' '產地' '價錢(斤)';'柳丁' '冬' '豐原' 20;'芒果' '夏' '玉井' 30;...
'草莓' '冬' '大湖' 50;'荔枝' '夏' '台南' 45;'蘋果' '一年四季' '梨山' 25};
xlswrite('D:\Physical Therapy\Graduate School\Class\碩二上\MATLAB Class\fruit.xls',F,'Sheet1');
[N,T,rawdata]=xlsread('D:\Physical Therapy\Graduate School\Class\碩二上\MATLAB Class\fruit.xls')

執行結果:

建立excel檔案與存放路徑
擷取結果
其中N為數值陣列,T為字串陣列,rawdata則包含所有資料內容(為一細胞陣列)

沒有留言: