创建一个程序,在矩阵中显示大于0.8的数字

问题描述

这里是新程序员,

我的任务是制作一个程序,该程序选择并显示带有2个for循环的5x6随机矩阵中有多少个大于0.8的数字,如果有人知道如何制作它,将不胜感激。

谢谢。

我正在用八度书写,

代码是这样开始的:

clear

clc

rand(5,6);

for row =….

解决方法

希望此MATLAB代码可以延续到Octave。第一种方法使用两个for循环扫描/遍历矩阵。如果在扫描Matrix(Row,Column)期间从矩阵检索的值大于0.8,则变量Number递增。重复此过程,直到检查了整个矩阵。 Numbers_Greater_Than用于存储所有大于0.8的数字。

使用循环:

clear;
clc;
Matrix = rand(5,6);
Numbers_Greater_Than = [];
[Number_Of_Rows,Number_Of_Columns] = size(Matrix);


Number = 0;
for Row = 1: Number_Of_Rows
    for Column = 1: Number_Of_Columns

    if(Matrix(Row,Column) > 0.8)
        Number = Number + 1;
        Numbers_Greater_Than = [Numbers_Greater_Than Matrix(Row,Column)];
    end
    end
end

fprintf("The are %d numbers greater than 0.8 in the matrix\n",Number);
Numbers_Greater_Than

扩展名:

或者: 使用单个数字索引扫描元素。

clear;
clc;
Matrix = rand(5,6);

Number = 0;
for Element = 1: numel(Matrix)   

    if(Matrix(Element) > 0.8)
        Number = Number + 1;
    end
     
end

fprintf("The are %d numbers greater than 0.8 in the matrix\n",Number);

使用逻辑数组:

此方法根据条件> 0.8创建一个逻辑数组。当条件为真时,Logical_Array设置为“ 1”,而条件为假时,clear; clc; Matrix = rand(5,6); Logical_Array = Matrix > 0.8; Number = sum(Logical_Array,'all'); fprintf("The are %d numbers greater than 0.8 in the matrix\n",Number); 设置为“ 0”。通过随后求和,可以计算矩阵中条件为真的次数。

    Destination2 = GameObject.FindGameObjectsWithTag("Storehouses");        // storehouse distance should be based off  production
    
    Vector3 position = transform.position;
    for (int i = 0; i < Destination2.Length; i++) // put in 10 storehouses,find the closest distance to the colonist
    {
        Debug.Log("1");
        buildingInformation[i].buildingID2 = Destination2[i];      // stores game objects 0,1
        

        Vector3 direction = (Destination2[i].transform.position - position);
        float distance = direction.sqrMagnitude;

        buildingInformation[i].buildingDistance2 = distance;
        Array.Sort<BuildingInformation>(buildingInformation,(x,y) => x.buildingDistance2.CompareTo(y.buildingDistance2));// smallest to largest
        
    }
    Supplier = buildingInformation[0].buildingID2;

使用MATLAB R2019b运行