# Translating vector into locations in a matrix

조회 수: 4 (최근 30일)
Mark . 2013년 3월 9일
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

댓글을 달려면 로그인하십시오.

### 채택된 답변

Cedric Wannaz 2013년 3월 9일
편집: Cedric Wannaz 님. 2013년 3월 9일
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이전 댓글 1개 표시이전 댓글 1개 숨기기
Cedric Wannaz 2013년 3월 10일

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by