matlab - 输出矩阵大小 n x m,当索引之和为偶数时为 1,否则为 0

标签 matlab matrix

我尝试将以下内容作为一种爱好,而不是作为家庭作业。在 使用 MATLAB 进行计算机编程:J. Michael Fitpatrick 和 Akos Ledeczi 中,有一个练习题提出了这样的问题:

Write a function called alternate that takes two positive integers, n and m, as input arguments (the function does not have to check the format of the input) and returns one matrix as an output argument. Each element of the n-by-m output matrix for which the sum of its indices is even is 1. All other elements are zero.

之前的问题是类似的,我编写了一个非常简单的函数来完成它的要求:

function A = alternate(n,m)
    A(1:n,1:m)=0;
    A(2:2:n,2:2:m)=1;
    A(1:2:n,1:2:m)=1;
end

现在我的问题是,这足够好吗?它准确地输出它所要求的内容,但它不检查总和。到目前为止,我们还没有讨论嵌套 if 语句或任何类似的内容,我们只是开始讨论非常基本的函数。我觉得赋予它更多的功能可以让它更好地回收以供将来使用。

最佳答案

很高兴看到您正在学习,学习任何编程语言的第一步应该是确保您始终添加相关注释!这对您和任何阅读您的代码的人都有帮助。所以第一个改进是这样的:

function A = alternate(n,m)
% Function to return an n*m matrix, which is 1 when the sum of the indices is even
    A(1:n,1:m)=0;      % Create the n*m array of zeros
    A(2:2:n,2:2:m)=1;  % All elements with even row and col indices: even+even=even
    A(1:2:n,1:2:m)=1;  % All elements with odd row and col indicies: odd+odd=even
end

但是,您可以使其更简洁(折扣评论),并且可能更清楚地与摘要相关:

function A = alternate(n,m)
% Function to return an n*m matrix, which is 1 when the sum of the indices is even
    % Sum of row and col indices. Uses implicit expansion (R2016b+) to form 
    % a matrix from a row and column array
    idx = (1:n).' + (1:m); 
    % We want 1 when x is even, 0 when odd. mod(x,2) is the opposite, so 1-mod(x,2) works:
    A = 1 - mod( idx, 2 );
end

这两个函数都做同样的事情,您应该使用个人喜好(以及与大问题相关的性能)。

我认为,即使没有评论,我写的更清楚的替代方案也如其所言。您不必知道摘要即可了解您正在寻找偶数索引总和,因为我已经完成了总和并测试了是否为偶数。您的代码需要解释。

它也可以写成一行代码,而索引方法则不能(正如您所做的那样)。

A = 1 - mod( (1:n).' + (1:m), 2 ); % 1 when row + column index is even

关于matlab - 输出矩阵大小 n x m,当索引之和为偶数时为 1,否则为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56060126/

相关文章:

matlab - 在 Matlab 中使用字符串进行 foreach 循环

matlab - 如何在 Simulink Matlab 功能 block 中使用 syms

java - 为什么我的逆投影矩阵的两个元素始终为 0?

arrays - MATLAB迭代添加数组元素: time behavior

arrays - 如何在 Matlab 中将数组打印到 .txt 文件?

matrix - : One matrix is row/col permutation of another matrix 的复杂度

python - 从 Numpy 中的 2 个向量形成矩阵,重复 1 个向量

matrix - 离散勒让德多项式的 Octave 矩阵

c++ - 如何用OpenCV模拟Matlab的medfilt2?

java - java中该三维数组沿第三维的平均值