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?

Risposte (3)

Azzi Abdelmalek
Azzi Abdelmalek il 10 Feb 2014
Modificato: Azzi Abdelmalek il 10 Feb 2014
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
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 il 10 Feb 2014
Modificato: Jason il 10 Feb 2014

0 voti

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 Commenti

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.
Jason, Edit your question or add a comment to any answer of your choice by clicking on comment on this answer

Questa domanda è chiusa.

Richiesto:

il 10 Feb 2014

Chiuso:

il 20 Ago 2021

Community Treasure Hunt

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

Start Hunting!

Translated by