James Matthews
James Matthews

Reputation: 9

Matrices in Matlab

I'm running a script calling a function and within the function it takes a value from the matrix. Matlab seems to be thinking that the value is still a matrix and is asking for a . when its squared. I should be getting a single value out of my matrix. Any help would be appreciated!

Output

Error using ^ Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead.

Error in ls_error (line 11) partialSum = (vi - yi)^2;

This is the script i'm running

Exp1H1 = 35.6;
Exp1H2 = 24.7;
Exp2H1 = 46.8;
Exp2H2 = 37.8;
Exp3H1 = 45.7;
Exp3H2 = 36.4;
Exp4H1 = 47.7;
Exp4H2 = 39.2;

Radius = 3.75;
L = 10;

ArrayOfHeightDiff = [(Exp1H1-Exp1H2),(Exp2H1-Exp2H2),(Exp3H1-Exp3H2),       (Exp4H1-Exp4H2)];
dhdl = ArrayOfHeightDiff./L
ArrayOfDarcys = [0.29,0.25,0.26,0.23];
v_meas = ((ArrayOfDarcys.*1000)./60)./(pi*Radius^2)

K = [-0.3 : 0.1 : 0.5];

for ii = 1 : 1 : length(K)
    ExportSum = ls_error(dhdl, v_meas, K)
    ExportSum(1,ii) = ExportSum
end

This is the function

function [ExportSum] = ls_error(dhdl, v_meas, K)

total = 0;           
L = length(dhdl);   

for ii = 1 : 1 : L
    dhdl1 = dhdl(1,ii);
    vi = v_meas(1,ii);        

    yi = 1*K* dhdl1;    
    partialSum = (vi - yi)^2;   
    total = total + partialSum;     
end

ExportSum = total;
end

Upvotes: 0

Views: 64

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

In the calling script you define K as a vector. Therefore, in the function yi is a vector too. Hence the error in (vi - yi)^2.

Upvotes: 1

Matt Taylor
Matt Taylor

Reputation: 3408

In the following code, you create a 1xN vector K, and pass it into ls_error:

K = [-0.3 : 0.1 : 0.5];

for ii = 1 : 1 : length(K)
    ExportSum = ls_error(dhdl, v_meas, K)
    ExportSum(1,ii) = ExportSum
end

You then use this vector Kand multiply it by two scalars, which will produce a 1xN vector:

yi = 1*K* dhdl1;    
partialSum = (vi - yi)^2;   

The partialSum calculation is then giving you the error, as you can't perform a scalar square on a vector.

From your code, what I think you meant to do was this:

for ii = 1 : 1 : length(K)
    ExportSum = ls_error(dhdl, v_meas, K(ii))
    ExportSum(1,ii) = ExportSum
end

Where instead of passing in the entire vector K, you just want to pass in the iith element to use within the calculation of ExportSum which you return.

As a further note, once this bug is solved, it may be worth looking at vectorising your Matlab function (i.e. deliberately passing it the entire vector of K and computing all of the ExportSums at once using vector arithmetic instead of inside a loop), which will hugely speed up your code. It can be complicated, but will likely give you a huge decrease in execution time.

Upvotes: 2

Related Questions