Error using * Inner matrix dimensions must agree.

clc
clear all
close all
format short
% define function
A = 0.42748; B = 0.08664;
P_r = (0:2:10);
T_r = [1 1.2 1.4 2 0 0];
% Function in f(x)=0
f =@(Z)Z^3-Z^2+(A.*(P_r./T_r.^(5/2))-B.*(P_r./T_r.*(1+B.*(P_r./T_r)))).*Z-A*B*(P_r.^2./T_r.^(7/2));
xu = 6;% Upper initial guess
xl = 0;% Lower initial guess
xm=0; % first midpoint value
fprintf('\n\n\n Bisection using a For Loop\n')
fprintf('The initial guess of xl, xu %10.4f, %10.4f\n', xl,xu)
for i = 1:15
xold = xm;
if f(xm)*f(xu)<0
xl=xm;
else
xu=xm;
end
xm=(xu+xl)/2;
ea=abs((xm-xold)/xm)*100;
fprintf(['iteration ',num2str(i),' xl, xu, ea: %10.4f, %10.4f, %10.4f\n'],xl,xu,ea)
xold = xm;
end
please help, im getting Error using * Inner matrix dimensions must agree

Answers (2)

KSSV
KSSV on 14 Jul 2017
Edited: KSSV on 14 Jul 2017
Replace line:
f(xm)*f(xu)<0
with
f(xm).*f(xu)<0
Read about element by element operations in MATLAB. Note that you are multiplying two vectors there. Think whether you expect a array as output or a scalar as output.
If you expect a scalar, that line should be :
f(xm)*f(xu)'<0

2 Comments

Thank you that worked, may i also ask why this code
clear all ; close all ;
clc ;
format long
% Function in f(x)=0
f=@(x)-26+85*x-91*x.^2+44*x.^3-8*x.^4+x.^5;
xu = 1;% Upper initial guess
xl = 0.5;% Lower initial guess
xm=0; % first midpoint value
fprintf('\n\n\n Bisection using a For Loop\n')
fprintf('The initial guess of xl, xu %10.4f, %10.4f\n', xl,xu)
for i = 1:5
xold = xm; % save the mid point
% Check the interval between which the root lies
if f(xm)*f(xu)<0
xl=xm; % the midpoint becomes the lower guess
else
xu=xm; % the midpoint becomes the upper guess
end
xm=(xu+xl)/2; % compute the midpoint
% Calculate relative approximate error
ea=abs((xm-xold)/xm)*100;
fprintf(['iteration ',num2str(i),' xl, xu, ea: %10.4f, %10.4f, %10.4f\n'],xl,xu,ea)
xold = xm; % save the mid point
end
...works and actually find roots, however my equation returns zeros for all values of xu, xl, and ea
In the above code when you substitute xm , xu in f it gives a number, so * worked. Where as in the old script on substituting those values into f, the result was a vector. I think you need to check your f, rethink on your code.

Sign in to comment.

f(x) with a scalar argument x returns a vector of length 6.
For two vectors of length 6, the product f(xm)*f(xu) is not defined.
Formally, f(xm).*f(xu) should work, but I don't know if it makes sense in your context.
Best wishes
Torsten.

Categories

Asked:

on 14 Jul 2017

Commented:

on 14 Jul 2017

Community Treasure Hunt

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

Start Hunting!