When I run the following code, matlab shows me an error that the index exceeds matrix dimensions. It seems like it has an easy solution, but I am still relatively new to matlab and coding in general.
Some background info if required, I'm trying to validate a thermal model and x2 is reduced temperature and yp is predicted thermal efficiency. p1 and p2 depict my thermal coefficients.
Hope you can help me out!
k1 -> constant
x2 -> 100x1 (double)
p1 = [0:0.1:10]; %100 elements
p2 = [0:0.001:1]; %1000 elements
for m=1:length(p1)
for n=1:length(p2)
yp(m,n) = ((k1.*p2(m,n))./(p1(m,n)+p2(m,n)))-((x2(m,n).*(p1(m,n).*p2(m,n)))./(p1(m,n)+p2(m,n)));
end
end

 Accepted Answer

madhan ravi
madhan ravi on 26 Aug 2018
Edited: madhan ravi on 26 Aug 2018
k1 = 30
x2= [1:100]'
p1 = linspace(0,10,100); %100 elements
p2 = linspace(0,1,100); %100 elements
P=p1+p2
PP = p1.*p2
yp = ((k1*p2)./(P))-((x2.*(PP))./(P))

5 Comments

madhan ravi
madhan ravi on 26 Aug 2018
Edited: madhan ravi on 26 Aug 2018
NOTE : x2 and k were given as examples.
The error arises because p1 and p2 aren't equal in dimensions.
There is no need for loop here.
Thanks madhan! Yes you were right, there is no need for a loop here, and your code worked till some extent.
Any idea how I can make it work for varying element sizes of p1 and p2?
madhan ravi
madhan ravi on 26 Aug 2018
Edited: madhan ravi on 26 Aug 2018
I’m not sure of it but what I know is if the sizes of p1 and p2 vary you can’t add them because there will be some mismatches. What you can do is you can add zeros to the vector which is deficient of elements so that both the vectors will have the same length.
An example:
v1 = [1:8 zeros(1,2)]
v2 = [1:10]
V = v1+v2
Thanks a lot madhan, will test it out. Vector addition should work.

Sign in to comment.

More Answers (0)

Products

Release

R2017b

Community Treasure Hunt

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

Start Hunting!