Program doesn't calculate with input

12 次查看(过去 30 天)
N/A
N/A 2014-1-16
回答: Amit 2014-1-16
My program is supposed to take input and use this to calculate the corresponding hydrogen. My code is this:
function Q = hydrogenusage(P)
P = 0:1:4000;
Q = 79.987*P+42.942;
plot(P,Q)
xlabel('Power (W)')
ylabel('Usage (l/minute)')
title('Hydrogen usage (no leak)')
axis([0 60 0 4000])
grid on
if nargin == 0
Q = input('Enter the power to get the hydrogen usage: ');
%This needs a reference to the power of the program by Erik Rijckaert.
end
Entering 'hydrogenusage' gives me:
Enter the power to get the hydrogen usage
I enter for an example 40
If I fill that in my formula it gives me Q = 3242.422.
But when I enter 40 it gives me this:
ans =
40
It looks wonderful and it very accurately repeats what I just entered but I'd like it to give me the answer of the function.
How can I make this happen?
  1 个评论
N/A
N/A 2014-1-16
To make clear: P is my input, my 'x' and Q is my output, my 'y'. I forgot to say I also tried this:
Q = input('Enter the power to get the hydrogen usage: ');
And I changed that to:
P = input('Enter the power to get the hydrogen usage: ');
That gave me a matrix as answer. It looks neat, but it's not what I need.

请先登录,再进行评论。

回答(2 个)

Walter Roberson
Walter Roberson 2014-1-16
The first few lines of your code ignore any parameter passed in and assign a vector to P and assign a vector of values to Q based upon that vector. Then the bottom portion tests whether any parameters were passed (even though they were otherwise ignored) and if not then uses input() to overwrite the Q (or P?) that had been assigned before, but does not calculate any Q value.
I suggest,
function Q1 = hydrogenusage
P = 0:1:4000;
Q = 79.987*P+42.942;
plot(P,Q)
xlabel('Power (W)')
ylabel('Usage (l/minute)')
title('Hydrogen usage (no leak)')
axis([0 60 0 4000])
grid on
Pt = input('Enter the power to get the hydrogen usage: ');
Q1 = interp1(P, Q, Pt);

Amit
Amit 2014-1-16
I am not sure if why you defining P inside the function if you are taking it as a input. Moreover, I think you need to ask for input before doing any calculations. Something like this:
function Q = hydrogenusage(P)
%P = 0:1:4000;
if nargin == 0
P = input('Enter the power to get the hydrogen usage: ');
%This needs a reference to the power of the program by Erik Rijckaert.
end
Q = 79.987*P+42.942;
plot(P,Q)
xlabel('Power (W)')
ylabel('Usage (l/minute)')
title('Hydrogen usage (no leak)')
axis([0 60 0 4000])
grid on

类别

Help CenterFile Exchange 中查找有关 Quantum Mechanics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by