【问题标题】:How do I shift columns (left or right) in a matrix?如何在矩阵中移动列(左或右)?
【发布时间】:2023-03-10 06:54:02
【问题描述】:

我想非循环移动我的矩阵,然后将零填充到左侧或右侧(取决于移位),即如果矩阵向右移动,零将被填充到左侧。

我使用的是 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

提前谢谢你

【问题讨论】:

    标签: matlab for-loop if-statement shift


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      相关资源
      最近更新 更多