从具有特定条件的旧矩阵生成新矩阵

时间:2016-05-13 14:23:14

标签: matlab

我有矩阵R(100*100),我想生成新的矩阵A(100*100),如下所示

如果我有频率添加新条件(let us say frequency = 20)。这意味着我的域名中将有五个条件`(100/20)= 5

From 1 to 20, from 21 to 40, from 41 to 60, from 61 to 80, and from 81 to 100.

让我们假设我的原始矩阵是

 [1 1 1……..1]

 [2 2 2 …….2]

 [3 3 3 ………3]

 And so on

[100 100 100 …..100]

新矩阵必须

From 1 to 20 same as old matrix

[1 1 1……..1]

[2 2 2 …….2]

[3 3 3………3]

From 21 to 40

A(21,j)=R(21,j)+R(1,j)   (row 21 + row 1)

A(22,j)=R(22,j)+R(2,j)   (row 22 + row 2)

A(23,j)=R(23,j)+R(3,j)   (row 23 + row 3)

And so on

From 41 to 60

A(41,j)=R(41,j)+R(21,j) +R(1,j)  (row 41+row 21 + row 1)

A(42,j)=R(42,j)+R(22,j) +R(2,j)  (row 42+row 22 + row 2)

And so on
A(81,j)=R(81,j)+R(61,j)+R(41,j)+R(21,j)+R(1,j)  (row 81+row 61 + row 41 + row 21+ row 1)

每次达到频率时,我都会遇到新情况。 我的问题是有没有足够的方法来做到这一点?我写了我的代码和它的工作正常,但每次我改变频率我会有一个新的条件。对于上面的情况,我有5 conditions,但如果我使用frequency 5,我将20 conditions,我需要更改所有方程式。我的意思是我需要代码才能处理任何频率

我在下面写了代码

clc;
clear;
prompt = 'Enter Frequency=';       %Frequency=20
N= input(prompt);
Frequency=N;
one_step=1/Frequency;              %Frequency
time=Frequency*one_step;
number_of_steps=time/one_step;     %Number of steps until next condition
total_steps=100;
R1 = rand(100,100);
Number_of_Lines=(total_steps/number_of_steps)+1;  %100/20
A(100,100)=0;
    for i=1:100
    for j=1:100
        if i>=1 && i<=number_of_steps
            A(i,j)=R1(i,j);
        elseif i>number_of_steps && i<= 2*number_of_steps
                A(i,j)=R1(i,j)+R1(i-number_of_steps,j);
        elseif i>2*number_of_steps && i<= 3*number_of_steps
                A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j);
        elseif i>3*number_of_steps && i<= 4*number_of_steps
                A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j)...
                    +R1(i-3*number_of_steps,j);
        elseif i>4*number_of_steps && i< 5*number_of_steps
                A(i,j)=R1(i,j)+R1(i-number_of_steps,j)+R1(i-2*number_of_steps,j)...
                    +R1(i-3*number_of_steps,j)+R1(i-4*number_of_steps,j);

        end
end

end

1 个答案:

答案 0 :(得分:1)

使用此模板并转换为您的案例

rows=100; cols=4; split=5;
x=ones(rows,cols);
c=mat2cell(x,repmat([rows/split],1,split),[cols]);
for i=[2:split]
  c{i,1}=c{i,1}+c{i-1,1};
end;

现在c的单元格包含您需要的总和。在这里,我使用了x矩阵来显示正在累积的总和,用你的真实矩阵替换。维也可以从给定的矩阵中导出。