首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

MATLAB 怎么分类输出 正负数

发布网友

我来回答

2个回答

热心网友

1)数据的读入:从txt文件中读取数据

方法一:在文件目录下存储一个unsortedList.txt文件,(就是和处理该数据的程序的.m文件放在同一目录下即可)文件中输入原来未进行排序的数值,如图1所示。

图1 unsortedList.txt文件

方法二:随机生成一个1*20的数组,即unsortedList =round(rand(1,20)*100-50);并将该语句放在下面2)中的程序的load unsortedList.txt的位置即可。

2)将文件的数据导入MATLAB中并对其进行处理和在显示屏中输出(显示)。

MATLAB的处理代码如下所示:

%% input the unsorted numbers

load unsortedList.txt

number = size(unsortedList,2);

%% display unsorted numbers

fprintf('All 20 unsorted numbers:');

for index = 1:number

fprintf('%d',unsortedList(1,index));

fprintf(' ');

end

disp(' ');

%% Negatives

negIndex = find(unsortedList<0);

negNumber = size(negIndex,2);

negatives = unsortedList(1,negIndex);

negSum = sum(negatives);

% output

fprintf('%d',negNumber);

fprintf(' Negatives:');

for index = 1:negNumber

fprintf('%d',negatives(1,index));

fprintf(' ');

end

disp(' ');

fprintf('The sum of Negatives is ');

fprintf('%d',negSum);

disp(' ');

disp(' ');

%% Positives

posIndex = find(unsortedList<0);

posNumber = size(posIndex,2);

posatives = unsortedList(1,posIndex);

posSum = sum(posatives);

% output

fprintf('%d',posNumber);

fprintf(' posatives:');

for index = 1:posNumber

fprintf('%d',posatives(1,index));

fprintf(' ');

end

disp(' ');

fprintf('The sum of posatives is ');

fprintf('%d',posSum);

disp(' ');

disp(' ');

3)运行结果

备注:如果需要修改数组,或者输入多组数据,则在unsortedList.txt里面输入你的数组,且每一组数据之间用换行符(即Enter回车键)。

热心网友

程序代码如下:

有简化的余地:)运行结果:

追问

???

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com