MATLAB: How to replace and join 2 matrix with one of them is random generated matrix

matrix manipulationmatrix modificationsreplace matrix

I'm try to solve a lil bit difficult problem and i wish you could join me to solve it.
I have a matrix like this
no. code x y P Q A B C D w
data1 : [ 1 1 1.06 0 0.0 0.0 0.0 0.0 0 0 0
2 2 1.043 0 21.7 12.7 40.0 0.0 -40 50 0
3 0 1.0 0 2.4 1.2 0.0 0.0 0 0 0
4 0 1.06 0 7.6 1.6 0.0 0.0 0 0 0
5 2 1.01 0 94.2 19.0 0.0 0.0 -40 40 0
6 0 1.0 0 0.0 0.0 0.0 0.0 0 0 0
7 0 1.0 0 22.8 10.9 0.0 0.0 0 0 0
8 2 1.01 0 30.0 30.0 0.0 0.0 -10 40 0
9 0 1.0 0 0.0 0.0 0.0 0.0 0 0 0
10 0 1.0 0 5.8 2.0 0.0 0.0 0 0 19
11 2 1.082 0 0.0 0.0 0.0 0.0 -6 24 0
12 0 1.0 0 11.2 7.5 0.0 0.0 0 0 0
13 2 1.071 0 0.0 0.0 0.0 0.0 -6 24 0
14 0 1.0 0 6.2 1.6 0.0 0.0 0 0 0
15 0 1.0 0 8.2 2.5 0.0 0.0 0 0 0]
and then I generate a matrix randomly we call this 'data2'. To generate this matrix I have to put a number as an input with range between 1-3. If i put '1' then data2 will generate matrix 1×2. If i put '2' then data2 will generate matrix 2×2. If i put '3' then data2 will generate matrix 3×2. And the first column of data2 must be integer. For example if i put '3', data2 will generate the matrix like below:
M N
data2 = [ 1 5.2
7 3.5
10 7.7]
From the example of data2, column M used to replace column 'no.' and column N used to replace column A. The value of column M show us where to replace the value of column N in A.
  • When the value of M is 7, then the value of A in row 7 which is '0.0' replace by '3.5' as the value of N. And the column 'code' in row 7 which is '0' change to '2'.
  • When the value of M is 10, then the value of A in row 10 which is '0.0' replace by '7.7' as the value of B. And the column 'code' in row 10 which is '0' change to '2'.
So the changes in every rows followed by the changes in row 'code' from '0' to '2'.
But there is an exception, let's see the column 'code' in data1. There are 3 kind of codes in that column, 1,2, and 0. Any generated number in data2 it will not change the value in column A, IF that value has code '1' or '2'. Changes only apply for the value in column A if that value has code '0'.
This program will loop with 100 of maximum iterations, and in every iteration, data2 will generated randomly.
Does anyone have the solution..?
Thanks.

Best Answer

A dull FOR loop approach as proof of concept:
for i2 = 1:size(data2, 1)
index = data2(i2, 1);
if data1(index, 2) == 0
data1(index, 7) = data2(i2, 2);
end
end
Does this match your needs already? Then the solution would be much shorter than the problem description.