Search code examples
matlabmatrixvectorindexing

How do you replace row vectors in a matrix using user defined input in Matlab?


Please I have a matrix that is formed from row vectors. I want to be able to use new user defined vector to replace the existing vectors in the matrix. For example,

A = [1 2 3]
B = [10 13 5]
C = linspace(1,2,3)
D = linspace(2,4,3)
E = [A B;C D];

I want to the user to be able to input a new A,B,C or D vector and use it to replace the existing vector in matrix E.

I have tried the changem command (which partially works). But the problem with that is you have to know the specific vector you want to change. I want a situation where the user can input any vector i.e. either A,B,C or D, and the program find the corresponding vector in the E matrix and replace it with the new one


Solution

  • I understand that the problem is changing either of the four row vectors based on the user inputs and so then change the values in E. Hence, first of all, MATLAB needs to know which vector to update and consequently the user has to give the name of the vector desired to be changed and then the new values will be given. Here, I tried to solve it as follows. Hope this will help.

    A = [1 2 3]
    B = [10 13 5]
    C = linspace(1,2,3)
    D = linspace(2,4,3)
    E = [A B;C D];
    
    g = input('Enter 1 for A, 2 for B, 3 for C, 4 for D: ');
    switch g
        case 1
            A = input('Enter new values for A: ');
            E(1, 1:3) = A;
        case 2
            B = input('Enter new values for B: ');
            E(1, 4:6) = B;
        case 3
            C = input('Enter new values for C: ');
            E(2, 1:3) = C;
        case 4
            D = input('Enter new values for D: ');
            E(2, 4:6) = D;
    end
    E