Assigning values from one array to another if certain specifications are met.

1 回表示 (過去 30 日間)
Tadas Grauzinis
Tadas Grauzinis 2020 年 4 月 13 日
編集済み: Adam Danz 2020 年 4 月 13 日
I have a few arrays
A= 0 1 2 3 6 8 9 10
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
B= 20 5 15 10
9 8 2 1
C= 10 15
9 3
Bassically the first row of A contains special points from a line that goes from 0 to 10 and the other two rows are where the values from B( to second row) and C( to third row) should go. Second rows of B and C are corresponding points from the first row of A.
For example. Since B(2,1)=A(1,7) then B(1,1) should go to A(2,7) like this:
A= 0 1 2 3 6 8 9 10
0 0 0 0 0 0 20 0
0 0 0 0 0 0 0 0
The final result should look like this:
A= 0 1 2 3 6 8 9 10
0 10 15 0 0 5 20 0
0 0 0 15 0 0 10 0
I am very much still a beginner in Matlab. I am writing a script that would calculate shear forces and bending moments of a cantilever beam so any advice and/or suggestions would be greatly appreciated.

採用された回答

Adam Danz
Adam Danz 2020 年 4 月 13 日
Inputs:
A= [ 0 1 2 3 6 8 9 10
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0];
B= [ 20 5 15 10
9 8 2 1];
C= [10 15
9 3];
Solution:
[isMatch, col] = ismember(B(2,:), A(1,:));
A(2,col(isMatch)) = B(1,isMatch);
[isMatch, col] = ismember(C(2,:), A(1,:));
A(3,col(isMatch)) = C(1,isMatch);
Result:
>> A
A =
0 1 2 3 6 8 9 10
0 10 15 0 0 5 20 0
0 0 0 15 0 0 10 0
  4 件のコメント
Tadas Grauzinis
Tadas Grauzinis 2020 年 4 月 13 日
What does isMatch do in A(2,col(isMatch))?
It seems to work with just col. I understand that if it would be just A(2,col) than it would be reffering to second row all col outputs(which are just what is needed), but what does (isMatch) add?
Adam Danz
Adam Danz 2020 年 4 月 13 日
編集済み: Adam Danz 2020 年 4 月 13 日
Good question. Suppose matrix B was
B= [ 20 5 15 10
9 8 200 1];
There is no match for 200 so col would return 0 for that match. A(2,col) would then return an error since indices must be positive, non-zero integers. So, col(isMatch) makes sure you're only selecting col values that correspond to matches. It's a safety net.

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

その他の回答 (1 件)

Kevin Hellemans
Kevin Hellemans 2020 年 4 月 13 日
編集済み: Adam Danz 2020 年 4 月 13 日
Hi,
I think this should do the trick:
A= [0 1 2 3 6 8 9 10; ...
0 0 0 0 0 0 0 0; ...
0 0 0 0 0 0 0 0];
B = [20 5 15 10; 9 8 2 1];
C=[10 15; 9 3];
A(2,B(2,:)) = B(1,:);
A(3,C(2,:)) = C(1,:);
disp(A)
  1 件のコメント
Tadas Grauzinis
Tadas Grauzinis 2020 年 4 月 13 日
It reads the second rows of B and C as a position and places first row elements like this.
A=[ 0 1 2 3 6 8 9 10 0;
10 15 0 0 0 0 0 5 20;
0 0 15 0 0 0 0 0 10]

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

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by