星期四, 11月 02, 2006

MATLAB課堂作業: 作業三

1. for i=1:50,
A(i)=i^2;
end;
A=reshape(A,5,10)
Find A. Is there any better way to find the same result?


ANS:
指令亦可改成
>> A=[1:50].^2;
>> A=reshape(A,5,10);
>> find(A)

ans =

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
如果只是要得到相同的結果,則亦可省略reshape的指令
>> A=[1:50].^2;
>> find(A)
但是單就如此,其結果顯示的矩陣排列方式和原本的結果不同
因此指令須改為
>> A=[1:50].^2;
>> find(A)’

2. Let A=magic(5). Replace the elements that are larger than 10 with 'NaN'

ANS:
>>clear all
>> A=magic(5)

A =

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

>> A(A>10)=NaN

A =

NaN NaN 1 8 NaN
NaN 5 7 NaN NaN
4 6 NaN NaN NaN
10 NaN NaN NaN 3
NaN NaN NaN 2 9

3. Replace the prime elements in Prob 2 with 0.

ANS:
本來以為題意是要將已經做過取代動作的矩陣中的質數以0取代,但是因為新矩陣中有非整數出現,因此無法執行isprime的指令找出質數。若是先將原本A矩陣中的質數代為0,再將新矩陣中>10的數值以NaN取代,其求出的解亦與原意不同,故不適用。若只是單純把原矩陣A中的質數代為0,其指令和結果如下:
>> clear
>> A=magic(5)

A =

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

>> A(isprime(A))=0

A =

0 24 1 8 15
0 0 0 14 16
4 6 0 20 22
10 12 0 21 0
0 18 25 0 9

4. The function draw_number is shown in sec 3.3. Please make a comparison of results when no_of_draw=[100:100:1000]?

ANS:
將no_of_draw=[100:100:1000]代入sec 3.3程式後執行所得之結果為
>> draw_number([100:100:1000])

ans =

17 18 20 21 24

由結果可知其抽籤之總次數為100次
和no_of_draw=100代入有相似之結果
>> draw_number(100)

ans =

17 24 20 20 19

其原因為:
在程式中的指令是在while n<=no_of_draw的前提下重複執行
而no_of_draw=[100:100:1000]相當於[100 200 300 400 500 600 700 800 900 1000]之陣列
當n<=100時,陣列中所有的條件皆成立,
>> 100<=[100:100:1000]

ans =

1 1 1 1 1 1 1 1 1 1
但是當n>100時,則陣列中至少有其中一個元素不成立
>> 101<=[100:100:1000]

ans =

0 1 1 1 1 1 1 1 1 1
因此以no_of_draw=[100:100:1000]代入程式中計算時,只會運算到第100次

5. Please use while...end statement to find out the chances to obtain a preset two-digit number which will be similar to the number set drawn from function rand().

ANS:
程式指令:
% chances_draw_number.m
% use while...end statement to find out the chances to obtain a preset
% two-digit number which will be similar to the number set drawn from
% function rand()

num=input('請輸入一個十位數字:');
no_of_draw=input('請輸入欲計算輸入數字與隨機號碼相同之次數:');
n=0;
for i=1:no_of_draw
while 1
ball=fix(rand*100);
if ball~=num
n=n+1;
else
break;end
chance(i)=1/n;
end
allchance=sum(chance(i))/no_of_draw*100;
end
fprintf('輸入數字 %d,與隨機號碼相同次數達 %d次的機率為 %0.3f%%\n',num,no_of_draw,allchance)

執行結果:
>> chances_draw_number
請輸入一個十位數字:12
請輸入欲計算輸入數字與隨機號碼相同之次數:5
輸入數字 12,與隨機號碼相同次數達 5次的機率為 0.059%

1 則留言:

ShuRuLin 提到...

第五題正解
clear all
k=input('Please input a number to compare? (0-100)');
l=input('Please input the total number to do?');
a=round(k);
n=0;
num=0;
answer=0;
if a>=0 & a<=100
for i=1:l
while round(rand*100)~=a
n=n+1;
end
num=num+1/n;
end
answer=num/100;
fprintf('%d%s%d%s%f\n',l,'次抽中和',a,'相同的號碼機率為千分之',answer*1000);
else
fprintf('%s\n','你所輸入的號碼範圍號碼不對')
end
可以同時輸入號碼跟比對次數