1 view (last 30 days)

Column 1 of array A contains the index number of the samples; other columns of matrix A contain other attributes of each sample, (in array B, the first two cell along each row contain an attribute and the index number of a sample). when I have one thousand rows, it becomes inefficient to use the code below. Please is there a more efficient way to write the code such that one does not have to input the thousands of numbers in the code.

Columns 2, 4 and 6 of array B contain the index number of samples contained in matrix A. I am trying to insert corresponding sample attribute in column 4 of array A (based on corresponding index number in array A and B) into new 3rd, 6th and 9th column of matrix B; to have matrix C as shown below:

A = [1,3.43,2.34,5.43,3.22;

2,8.32,6.34,7.34,2.34;

3,3.67,8.34,8.23,1.34;

4,2.67,6.89,4.99,8.65;

5,1.33,5.42,2.53,6.13];

B = [0.12,2,0.15,1,0.65,3;

0.33,5,0.62,4,0.55,1;

0.91,1,0.77,2,0.66,5];

The code below works but with over a thousand column, it becomes inefficient to write all the numbers in line 2 of the code below:

I am trying to write a code that does not require one to write all the numbers of the columns as in line 2 of the code below.

I get reasonable result with this code but having to type millions of numbers for every run makes it inefficient.

Z = [0;0;0];

C = [[B(:,1:2) Z B(:,3:4) Z B(:,5:6)]]; %Generating satic part

for j = 1:3 %generating dynamic part in loop

for i = 1:3

n = A(find(ismember(A(:,(1)), B(i,j*2), 'rows')),4);

C(i,j*3) = n;

end

end

Andrei Bobrov
on 24 Aug 2019

Edited: Andrei Bobrov
on 24 Aug 2019

m = size(B,1);

C = reshape(B,m,2,[]);

C(:,end+1,:) = reshape(A(B(:,2:2:end),4),m,1,[]);

C = reshape(C,m,[]);

or

m = size(B,1);

C = reshape(permute(reshape(B,m,2,[]),[1,3,2]),[],2);

C(:,3) = A(C(:,2),4);

C = reshape(permute(reshape(C,m,3,[]),[1,3,2]),m,[]);

Sign in to comment.

Allen
on 24 Aug 2019

It looks as if every other column of B is a row index corresponding the the rows of A. It also appears that C consists of pairs of columns from B followed by a new column, where this new column is equal to the 4th column of A at the row index in every other column of B. If this is correct then the sample code below should work with larger sized columns using the same pattern.

% Preallocate C with same #rows as B, but with 1 addtional column for every 2 columns in B

[r,c] = size(B);

C = zeros([r,3*c/2]);

for i = 1:c/2 % Loops through each pair of columns in B

C(:,3*i-2:3*i) = [B(:,2*i-1:2*i),A(B(:,2*i),4)];

end

There is likely a better method yet by using vectorized indexing, but this should be considerably more efficient.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.