【问题标题】:How to shift columns in a matrix to the right in MATLAB?如何在MATLAB中将矩阵中的列向右移动?
【发布时间】:2015-12-31 21:31:39
【问题描述】:

Given the following Problem: 我怎样才能做到这一点?我试图将列向右移动,但我只能让它们向左移动。我也无法解释最后的列被移到前面。我知道我需要使用某种临时数组,但我不知道如何实现它。

到目前为止我的代码:

function [B] = column_shift()

A = input('Enter an nx6 matrix: ')
interimA = A(:,6);
    for n = 1:5
        A(:,n) = A(:,n+1);
        interimA = A(:,1);

    end
B = A
end

【问题讨论】:

  • 你在循环中的分配是向后的。 =左边的变量被赋予右边事物的值。

标签: matlab matrix


【解决方案1】:

你可以使用circshift:

%# shift by 1 along dimension 2
shiftedA = circshift(A,1,2);

注意:CIRCSHIFT 已更改其定义。早期版本的 Matlab 只接受一个输入参数,因此您必须编写 circshift(A,[0,1])(沿第一维移动 0,沿第二维移动 1)才能获得与上述相同的结果。

如果您确实需要使用 for 循环,则可以执行以下操作:

shiftStep = 1;
%# create an index array with the shifted column indices
nCols = size(A,2);
shiftedIndices = circshift(1:nCols,shiftStep,2);

shiftedA = A; %# initialize the output to the same size as the input

%# for-loop could be replaced by shiftedA = A(:,shiftedIndices);
for iCol = 1:nCols
    shiftedA(:,iCol) = A(:,iCol==shiftedIndices);
end

【讨论】:

  • 我会使用 circshift,但问题是我需要使用 for 循环。
  • @user3006937,如果我告诉您在问题中包含完整的问题说明很有用,您会感到惊讶吗?请注意,“在图像文件中链接完整问题”在任何方面都没有用。
  • @user3006937 所以只需使用for ii = 42; shiftedA = circshift(A,1,2); end - 你可以包含一条消息disp(' Dear Mr. supervisor I don't need and shouldn't use a loop here!) ;)
【解决方案2】:

我已对您的代码进行了修改和注释版本。希望能帮助到你! 只是一些注意事项:

您将列向左移动是因为您正在移动第 n+1 列,而您应该使用 n-1 移动。

最后一列是在for循环之前处理的特殊情况(如果你真的需要在for循环内做所有事情,你可以在n = 1开始循环,检查循环是否在第一个列,并在那里处理“特殊转变”)。

您实际上并不需要临时数组。如果它可以帮助您使代码更易于理解,您可以创建一个,但在这种情况下我没有使用过。

function [B] = column_shift()

A = input('Enter an nx6 matrix: ')
B = A;
B(:,1) = A(:,end);              %copy the last column of A to the first column of B
    for n = 2 : size(A,2)       %starting on the second column of A, until the last column...
        B(:,n) = A(:,n-1);      %copy the column "n-1" on A to the column "n" in B
    end
end

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    相关资源
    最近更新 更多