Output matrix for simple function

I'm brand new to Matlab, and have created a very simple function here to calculate an ion's equilibrium potential:
function y = equipotent(n,X1,X2)
y = (58/n) * log10(X1/X2);
I'd like to do two things: 1) vary X2 for a set of values (1-100) while keeping X1 and n constant. and 2) store all the outputs from the function in a vector for plotting X2 vs y.
Anything helps! Thanks!

回答(2 个)

If you change your code to
function y = equipotent(n,X1,X2)
y = (58/n) * log10(X1./X2);
then it will give a vector output y for vector input X2, and you should be all set.
Hi Derek,
MATLAB has some useful ways to do what you're trying to do. If you use the (.*) operator instead of (*), it will perform a vector multiplication.
Therefore you can adjust your function as follows:
function y = equipotent(n,X1,X2)
y = (58 ./ n) .* log10(X1 ./ X2);
Then you can just run commands:
y = equipotent(4, 3, X2)
figure
plot(X2,y)
Did that help you out?

4 个评论

I changed the code and each time I run the function, the new output overrides the previous. Any ideas on how to record each output and store each one in the same matrix?
Ah, this sounds like the following code would help you:
n = 4;
X2 = (1:100)'; % Let's make it a vertical (100-by-1) vector
X1_set = 1:5; % Let's use 5 different values for X1
% So the result(s) can be collected in a 100-by-5 matrix
y_set = zeros(length(X2), length(X1_set));
for i = 1:length(X1_set)
y_set(:,i) = equipotent(n, X1_set(i), X2);
end
% And plot them
figure
plot(X2,y_set)
legend(num2str(X1_set'))
I'll update my answer accordingly. Is this what you were looking for?
Note that in your original question:
2) store all the outputs from the function in a vector for plotting X2 vs y
You only wanted to plot X2 (which is a 100-length vector) against y. In the original answer, putting the (.*) operator in the function lets you calculate y all-at-once so that y is also a 100-length vector. There should have been no need to run your function more than once.
In my comment above I've also showed how to store sets of y for different input via a loop. This is the only time where you'd need to run your function more than once (and therefore need to avoid overwriting your previous answer by putting y into columns of the y_set matrix.
I have one similar question ... I want ti make a function which will take p, v, d and D as input, and will calculate the pressure drop register (Dp), for d / D from 1 to d / D (derived from the input data), and in steps of (1/100 ) * (d / D)... How can i do it ?
The type of function is

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 EEG/MEG/ECoG 的更多信息

提问:

2014-4-14

评论:

2021-11-12

Community Treasure Hunt

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

Start Hunting!

Translated by