如何移动矩阵中的列(左或右)?
How do I shift columns (left or right) in a matrix?
我想非循环地移动我的矩阵,然后将零填充到左侧或右侧(取决于移动),即如果矩阵向右移动,零将填充到左侧。
我使用的是 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
提前致谢
这会将矩阵 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
我想非循环地移动我的矩阵,然后将零填充到左侧或右侧(取决于移动),即如果矩阵向右移动,零将填充到左侧。
我使用的是 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
提前致谢
这会将矩阵 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