-3

Here is my code:

x = 60: 95;
r11 = 0.93;
E1=13.5;
F1=0.00529;
G1=0;
H1=1;
k11=60;
k12=0;
uid = 10^-7*1.31275 * exp(0.145961 * x );
P = exp(-F1 * ((x-k11)^2) - G1*(x-k12));
fi= E1 * P + H1;
y1 = r1 * fi * uid;
plot(x,y1);

My error is:

Error using ^ (line 51)
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise matrix powers, use '.^'.

Error in ui12 (line 16)
P = exp(-F1 * ((x-k11)^2) - G1*(x-k12));

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
  • Please do a basic search before you post a question. Copy-pasting your question title into Google yielded the linked Q&A as first answer. I’m even sure you were presented the link when typing your question. – Cris Luengo Mar 13 '20 at 13:56

1 Answers1

2

The error refers to the snippet (x-k11)^2, where you subtract a scalar (k11) from an array (x, 1x36) and try to square the result. The problem is that the function ^ is the shortcut for the function mpower(), which is the matrix-power function and consequently expects a scalar or a matrix calculation as it essentially is

x^2 == x*x
x^3 == x*x*x

However, it does not know what to do with an array as x*x does not work (try do run rand(1,36)*rand(1,36), which will essentially raise the same error). It also suggests a solution: .^, which is the element-wise power function (in fact, the . in an arithmetic operation usually indicates that the following operation is conducted element-wise). This .^ is the shortcut for the "normal" power function as you would have expected in the first place. It performs the ^2 to every element of the array x.

x.^2 == power(x,2)

extended side note: To mimic the behavior of the element-wise operator ., you may want to have a look at the arrayfun function, which applies a certain function to every element of a matrix or array/vector. If you are a new with matlab (as I assume from your question), this hint may just confuse you.

x.^2 == arrayfun(@(a)mpower(a,2),x)
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
max
  • 3,915
  • 2
  • 9
  • 25