Replace matrix entries with entries from another matrix

11 ビュー (過去 30 日間)
Waseem Akhtar
Waseem Akhtar 2021 年 7 月 15 日
コメント済み: Waseem Akhtar 2021 年 7 月 15 日
There are two matrices A and B as under:
A = [0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0];
B = [1 1 1;2 2 2;3 3 3];
I want to create a third matrix C in which the columns of B replace columns of A incrementally i.e columns of B move inside A. For example:
C1 = [0 0 0 0 1;0 0 0 0 2;0 0 0 0 3];
C2 = [0 0 0 1 1;0 0 0 2 2;0 0 0 3 3];
C3 = [0 0 1 1 1;0 0 2 2 2;0 0 3 3 3];
C4 = [0 1 1 1 0;0 2 2 2 0;0 3 3 3 0];
  2 件のコメント
dpb
dpb 2021 年 7 月 15 日
I'm not at all sure what your sample C arrays are to represent as a "third matrix C", but note
>> fliplr(tril(ones(4,5)))
ans =
0 0 0 0 1
0 0 0 1 1
0 0 1 1 1
0 1 1 1 1
>>
to build the pattern...
Waseem Akhtar
Waseem Akhtar 2021 年 7 月 15 日
It's not a pattern, rather, the columns entries of B matrix should replace that of A matrix in a loop. For example, in the first increment the C matrix should be:
C1 =
0 0 0 0 1
0 0 0 0 2
0 0 0 0 3
In next increment, it should be:
C2 =
0 0 0 1 1
0 0 0 2 2
0 0 0 3 3
and likewise for next increments. You may better understand it by running the matrices defined in my query in the Matlab.
THanks

サインインしてコメントする。

採用された回答

Simon Chan
Simon Chan 2021 年 7 月 15 日
I do it in a cell array:
clear; clc;
A = [0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0];
B = [1 1 1;2 2 2;3 3 3];
combine = [A,B];
idx = -1:-1:-4;
M=arrayfun(@(x) circshift(combine,[0,x]),idx,'UniformOutput',false);
C = cellfun(@(x) x(:,1:5),M,'UniformOutput',false)
If you really want the name to be C1, C2, C3 and C4, then
C1 = C{1};
C2 = C{2};
C3 = C{3};
C4 = C{4};
  3 件のコメント
Simon Chan
Simon Chan 2021 年 7 月 15 日
Try the following:
However, the matrix C will be overwritten every time in the loop.
So additional manipulation on matrix C must be performed inside the loop.
clear; clc;
A = [0 0 0 0 0; 0 0 0 0 0; 0 0 0 0 0];
B = [1 1 1;2 2 2;3 3 3];
for idx = -1:-1:-4
M = circshift([A,B],[0,idx]);
C = M(:,1:5)
end
Result like this:
C =
0 0 0 0 1
0 0 0 0 2
0 0 0 0 3
C =
0 0 0 1 1
0 0 0 2 2
0 0 0 3 3
C =
0 0 1 1 1
0 0 2 2 2
0 0 3 3 3
C =
0 1 1 1 0
0 2 2 2 0
0 3 3 3 0
Waseem Akhtar
Waseem Akhtar 2021 年 7 月 15 日
That's it.
Thanks alot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by