Question

Problem: Solve linear equations

I have a 3×3 matrix and I wanted to take 3 expressions as inputs which contain matrix cells like

2*b(1,1)+3*b(1,2)+3*b(1,3)
3*b(2,1)+4*b(2,3)+3*b(2,3)

and evaluate them with different cell values in matrix

 0     1     0
 1     0     0
 1     0     0

 0     1     0
 0     1     0
 1     0     0  etc.,

I used the following code, I got the result but I can only use the cell values. When I try to give expressions with numeral, it shows the following error:

*Warning: File: pro.m Line: 5 Column: 9 The expression on this line will generate an error when executed. The error will be: Error using ==> vertcat CAT arguments dimensions are not consistent.

??? Error using ==> pro at 5 Error using ==> vertcat CAT arguments dimensions are not consistent.*

Here is my code:

clc;
clear all;
close all;

cell = ['b(1,1)+b(1,2)';'b(2,1)+b(2 ,3)';'b(3,3)+b(3,2)'];
exp = cellstr(cell);
res = [0,0,0];
display(res);

display(exp);

a = zeros(3,3);

for i = 1:1:3
    a(1,i) = 1;
    if(i>1)
    a(1,i-1) = 0;
    end
    for j = 1:1:3
        a(2,j) = 1;
        if(j>1)
        a(2,j-1) = 0;
        end    
        for k = 1:1:3
            a(3,k) = 1;
            if(k>1)
            a(3,k-1) = 0;
            end
            b = a;
            res(k) = eval(exp{k});
            if res(1) == 1 
                if res(2) == 1
                    if res(3) == 1 
                        display(res);
                        display(b);
                        break;
                    end
                end
            end
        end
        a(3,k)=0;
    end
    a(2,j) = 0;
end    
;

Help how can I input strings with numerals and matrix cells...

Was it helpful?

Solution

This is not a valid expression to initialize a cell in Matlab:

cell = ['b(1,1)+b(1,2)';'b(2,1)+b(2 ,3)';'b(3,3)+b(3,2)'];

You have to use the curly brackets { }:

cell = {'b(1,1)+b(1,2)';'b(2,1)+b(2 ,3)';'b(3,3)+b(3,2)'};

BTW, if you want to solve linear equation of the form AX+b=0, you can simply try X=-inv(A)*b

% Define system
A = [2 3 1; 7 -1 1; 4 0 5];
b = [1 0 1].';
% Solve system
X = -inv(A)*b; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top