Dont see why this code doesnt work

for i=1:11
x = z(i)/0.9;
pipeLength = sqrt(x.^2+z.^2);
if pipeLength <= 10
pipeCost(i) = price1*pipeLength
else
pipeCost(i) = price1*10 + price2*(pipeLength-10); % Price for lengths greater than 10 m
end
end
My program works fine up until this point.
I am trying to compute the cost of pipe depending on the length. Lengths up to 10 feet are 25 while anything after is 15. When I run the program it gives me the error,
In an assignment A(I) = B, the number of elements in B and I must
be the same.
Error in waterpipe (line 34)
pipeCost(i) = price1*10 + price2*((pipeLength)-10); % Price for
lengths greater than 10 m
any ideas?

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 10 日
編集済み: Azzi Abdelmalek 2014 年 2 月 10 日

0 投票

Use pipeCost(i,:) instead of pipeCost(i)
z=rand(1,11)
price1=1;
price2=2
for i=1:11
x = z(i)/0.9;
pipeLength = sqrt(x.^2+z.^2);
if pipeLength <= 10
pipeCost(i,:) = price1*pipeLength
else
pipeCost(i,:) = price1*10 + price2*(pipeLength-10);
end
end
Image Analyst
Image Analyst 2014 年 2 月 10 日

0 投票

When you say this
pipeLength = sqrt(x.^2+z.^2);
x is a scalar (single number), but z is an array. So pipeLength is an array of several numbers. Which means price1*10 + price2*(pipeLength-10) is also an array of several numbers. However you are trying to stick that array into a single element of pipeCost. Can't do that. It can be a whole row of pipeCost if you make pipeCost a 2D array, or make pipeLength a scalar:
pipeLength = sqrt(x.^2+z(i).^2);
Jason
Jason 2014 年 2 月 10 日
編集済み: Jason 2014 年 2 月 10 日

0 投票

With the way I have the code written, what is it that MATLAB doesnt like? All I can think of is that it doesnt want me to be subtracting from pipeLength in the way I have it.

2 件のコメント

Image Analyst
Image Analyst 2014 年 2 月 10 日
No. Did you not read my detailed explanation? Again, it doesn't like you stuffing a bunch of numbers into an array element that can take only a single number.
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 10 日
Jason, Edit your question or add a comment to any answer of your choice by clicking on comment on this answer

この質問は閉じられています。

質問済み:

2014 年 2 月 10 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by