重新排列使用Matlab中循环数组 [英] Rearranging an array using for loop in Matlab

查看:205
本文介绍了重新排列使用Matlab中循环数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个1×15阵列值:

I have a 1 x 15 array of values:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

我需要使用一个for循环将它们重新组合成一个3×5矩阵:

I need to rearrange them into a 3 x 5 matrix using a for loop:

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15

我将如何做呢?

推荐答案

我要告诉你三种方法。一,你需要有一个循环,两个人的时候你不在:

I'm going to show you three methods. One where you need to have a for loop, and two others when you don't:

首先,创建一个矩阵,3×5,然后跟踪的指数,将通过您的数组。之后,创建一个双循环,这将有助于您填充数组。

First, create a matrix that is 3 x 5, then keep track of an index that will go through your array. After, create a double for loop that will help you populate the array.

index = 1;
array = 1 : 15; %// Array we wish to access
matrix = zeros(3,5); %// Initialize
for m = 1 : 3
    for n = 1 : 5
         matrix(m,n) = array(index);
         index = index + 1;
    end
end

matrix =

  1     2     3     4     5
  6     7     8     9    10
 11    12    13    14    15

方法2 - 如果没有一个循环

简单地说,使用重塑

matrix = reshape(1:15, 5, 3).';

matrix =

  1     2     3     4     5
  6     7     8     9    10
 11    12    13    14    15

重塑将采取载体,并重组为一个矩阵,让你按列先填充矩阵。因此,我们希望把1〜5中的第一列,6至10中的第二和第11至15中的第三列。因此,我们的输出矩阵实际上是在5×3,当你看到这一点,这其实是在换位我们想要的矩阵,这就是为什么你做的版本。转置矩阵回来。

reshape will take a vector and restructure it into a matrix so that you populate the matrix by columns first. As such, we want to put 1 to 5 in the first column, 6 to 10 in the second and 11 to 15 in the third column. Therefore, our output matrix is in fact 5 x 3. When you see this, this is actually the transposed version of the matrix we want, which is why you do .' to transpose the matrix back.

您可以使用 vec2mat ,并指定你需要有5列值得你的矩阵:

You can use vec2mat, and specify that you need to have 5 columns worth for your matrix:

matrix = vec2mat(1:15, 5);

matrix =

  1     2     3     4     5
  6     7     8     9    10
 11    12    13    14    15

vec2mat 需要一个载体,如您在第二个参数中指定其重塑为多达列的矩阵。在这种情况下,我们需要5列。

vec2mat takes a vector and reshapes it into a matrix of as many columns as you specify in the second parameter. In this case, we need 5 columns.

这篇关于重新排列使用Matlab中循环数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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