如何在矩阵中移动列(左或右)?
Posted
技术标签:
【中文标题】如何在矩阵中移动列(左或右)?【英文标题】:How do I shift columns (left or right) in a matrix? 【发布时间】:2020-08-08 21:35:26 【问题描述】:我想非循环移动我的矩阵,然后将零填充到左侧或右侧(取决于移位),即如果矩阵向右移动,零将被填充到左侧。
我使用的是 MATLAB 2019b,到目前为止我的代码如下所示:
%dummy data
data = rand(5, 16);
channelSink = 9; %this variable will either be >layerIV, <layerIV or =layerIV
layerIV = 7;
diff = layerIV - channelSink;
for channel = 1:16
if channelSink > layerIV
%shift columns to the left by ab(diff)
%and
%set columns shifted by ab(diff) to zero
elseif channelSink < layerIV
%shift columns to the right by diff
%and
%set columns shifted by diff to zero
else %idiff = 0, don't shift
diff = 0;
disp('Sink at channel 7; not necessary to re-align');
end
end
提前谢谢你
【问题讨论】:
【参考方案1】:这会将矩阵data
水平移动d
位置,如果d
为正则向右移动,如果为负则向左移动,用零填充另一侧:
data = rand(5, 16); % example matrix
d = 3; % shift; positive/negative for right/left
result = zeros(size(data), 'like', data); % preallocate with zeros
result(:,max(1,1+d):min(end,end+d)) = data(:,max(1,1-d):min(end,end-d)); % write values
【讨论】:
以上是关于如何在矩阵中移动列(左或右)?的主要内容,如果未能解决你的问题,请参考以下文章