Filter löschen
Filter löschen

Translating vector into locations in a matrix

1 Ansicht (letzte 30 Tage)
Mark
Mark am 9 Mär. 2013
I'm attempting to set up an n row by 4 column matrix using data from column vectors Z1, Z2, & Z3. The problem is I need to place the random values from these column vectors into random locations in the n row by 4 column matrix. How can I specifically put certain values from the column vectors into certain locations in the K matrix? I know the K matrix will be always 4 columns wide, but could be any length. The rows of the K matrix will repeat every 4 utilizing a different value from one of the Z1, Z2, & Z3 column vectors. (I'm trying to come up with a local stiffness matrix that I can later transform into a global stiffness matrix). In the following code I'm attempting to set up a structure where the every 4th row in column 1 of Matrix K is row 1 - Z2(1,1), row 5 - Z2(5,1), row 9 - Z2(9,1), and so on. Any help would be appreciated.
K = zeros(4*member_count,4);
for r = 1:4:4*member_count;
for i = 1:Z2_count;
s(i,r) = Z2(i,1);
for j = 1:r
K(j,1) = s(i,r)
end
end
end

Akzeptierte Antwort

Cedric
Cedric am 9 Mär. 2013
Bearbeitet: Cedric am 9 Mär. 2013
If you need to generate random indices that can appear multiple times, you'll be interested in RANDI. Ex.:
>> randi(10, 1, 10)
ans =
1 9 10 7 8 8 4 7 2 8
you see here that 8 appears three times, and 5 doesn't appear.
If you need to shuffle indices randomly so you essentially have a random filling of K but indices must be unique, you'll be interested in RANDPERM. Ex.:
>> randperm(10)
ans =
2 7 3 10 4 1 9 5 6 8
you see here that all integers between 1 and 10 are present, but they were permuted randomly.
I don't fully understand what you want to do, but here one way to perform the last bit of your statement without a loop:
>> Z2 = (10:10:100).' % Simple example.
Z2 =
10
20
30
40
50
60
70
80
90
100
>> idx = 1:4:numel(Z2)
idx =
1 5 9
>> K = zeros(numel(Z2), 4)
K =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
>> K(idx,1) = Z2(idx)
K =
10 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
50 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
90 0 0 0
0 0 0 0
  2 Kommentare
Mark
Mark am 10 Mär. 2013
Thank you Cedric. This absolutely answered my question. I ended up using it multiple times in my situation.
K = zeros(4*member_count,4);
idx1 = 1:4:4*member_count;
K(idx1,1) = Z2;
K(idx1,2) = Z3;
K(idx1,3) = -Z2;
K(idx1,4) = -Z3;
Cedric
Cedric am 10 Mär. 2013
Great, I'm glad it helped!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Sparse Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by