您的位置:首页 > 编程语言 > MATLAB

2个简单的MATLAB程序

2007-08-16 11:36 393 查看
1、求1到n的阶乘之和 

运行结果:

 

>> add_factorial

please input n(0<n<171):20

add_factorial from 1 to n is:  

 

add_factorial =

 

  2.5613e+018

 

>> 

add_factorial.m源程序:

 

function add_factorial(n)
n=input('please input n(0<n<171):');

if (n>170 || n<0)
    disp(
'Error! please input n again!')
    break;
end
factorial=1;                   %0!=1
add_factorial=1;
for i=2:n
    factorial=factorial*i;
    add_factorial=add_factorial+factorial;
end
disp('add_factorial from 1 to n is:  ')
add_factorial

 

2、求矩阵X中的最大元素

运行结果:

 

>> max_element

please input a matrix X as [;;]:[1 2 3 4 5 ; 6 7 8 9 -1;-2 -3 0 9 6; 9 9 -2 3 0;-9 9 -1 5 2]

The max element in matrix X is:

 

max_element =

 

     9

 

There are <5> about the max element in matrix X

the indexs of  the max element in matrix X are :

 

Rows =

 

     2     3     4     4     5

 

 

Columns =

 

     4     4     1     2     2

 

>> 

max_element.m源程序:

function max_element(X)           .
X=input('please input a matrix X as [;;]:');
[h,l]=size(X);
max_element=X(1,1);
count=0;
for i=1:h
    for j=1:l
        if(X(i,j)==max_element)
             count=count+1;
             Rows(count)=i;
             Columns(count)=j;
         end       
        if(X(i,j)>max_element)
            max_element=X(i,j);
            count=1;
            Rows=zeros;
            Columns=zeros;
            Rows(1)=i;
            Columns(1)=j;
        end
    end
 end
 disp('The max element in matrix X is:')
 max_element
 fprintf('There are <%d> about the max element in matrix X ',count)
 disp('the indexs of  the max element in matrix X are :')
 Rows
 Columns

 

挺简单的,我做的还算细腻,注意了一些细节,若有错误及值得改进的地方,恳请您不吝指正!十分感谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matlab matrix input function