for或while循环在MATLAB中 [英] for or while loops in matlab

查看:201
本文介绍了for或while循环在MATLAB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始在编程类的matlab中使用for循环,基本的东西在做我很好,但我被要求使用循环创建一个3 x 5矩阵,其中每个元素的值是其行号与列号的乘方除以其行号与列号之和,例如元素(2,3)的值为(2 ^ 3/2 + 3) code> = 1.6



那么我需要使用什么样的循环来使我能够创建新行来形成矩阵? $ b

解决方案

由于您需要知道行和列号(因为您必须使用循环),for循环是一个自然的选择。因为for循环会自动跟踪你的行号和列号,如果你设置正确的话。更具体地说,你需要一个嵌套for循环,即一个循环在另一个循环内。外循环可能遍历行和例如通过列的内部循环。



至于startin g矩阵中的新行,这在循环中是非常糟糕的做法。你应该预先分配你的矩阵。这将对您的代码有重大的性能影响。预分配通常是使用 zeros 函数完成的。

例如

  num_rows = 3; 
num_cols = 5;
M =零(num_rows,num_cols); %//预分配内存,所以你不要在你的循环中增长你的矩阵
对于row = 1:num_rows
对于col = 1:num_cols
M(row,col)=(row ^ COL)/(行+ COL);
end
end

但是最有效的方法可能不是使用循环,但使用 ndgrid 执行一次:

  [R,C] = ndgrid(1:num_rows,1:num_cols); 
M =(R. ^ C)./(R + C);


I've just started using for loops in matlab in programming class and the basic stuff is doing me fine, However I've been asked to "Use loops to create a 3 x 5 matrix in which the value of each element is its row number to the power of its column number divided by the sum of its row number and column number for example the value of element (2,3) is (2^3 / 2+3) = 1.6

So what sort of looping do I need to use to enable me to start new lines to form a matrix?

解决方案

Since you need to know the row and column numbers (and only because you have to use loops), for-loops are a natural choice. This is because a for-loop will automatically keep track of your row and column number for you if you set it up right. More specifically, you want a nested for loop, i.e. one for loop within another. The outer loop might loop through the rows and the inner loop through the columns for example.

As for starting new lines in a matrix, this is extremely bad practice to do in a loop. You should rather pre-allocate your matrix. This will have a major performance impact on your code. Pre-allocation is most commonly done using the zeros function.

e.g.

num_rows = 3;
num_cols = 5;
M = zeros(num_rows,num_cols); %// Preallocation of memory so you don't grow your matrix in your loop
for row = 1:num_rows
    for col = 1:num_cols
        M(row,col) = (row^col)/(row+col);
    end
end

But the most efficient way to do it is probably not to use loops at all but do it in one shot using ndgrid:

[R, C] =  ndgrid(1:num_rows, 1:num_cols);
M = (R.^C)./(R+C);

这篇关于for或while循环在MATLAB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆