How can i save the variabels values as array form in for loop?

1 次查看(过去 30 天)
How can i save the variabels values as array form in for loop?
I want to save 'Q' as array or matrix form
loop = 1;
i = 0;
for N = 0:150
i=i+0.05;
....
....
Q = N_cells*i*(E_nernst - V_out);
%'N_cells' is constant.
%E_nernst & V_out are function of 'i'

回答(1 个)

TADA
TADA 2022-5-22
编辑:TADA 2022-5-22
You can define Q as a column/row vector. Its size can be set to the number of iterations you perform:
loop = 1;
i = 0;
maxN = 150;
N_cells = 10; % or the real constant value...
% This will preallocate the results as a column vector
% This bit is important for performance
% note that we add 1 to maxN because matlab has no index 0
Q = zeros(maxN+1, 1);
for N = 0:maxN
% if i isn't further changed in the loop body, you can also make i a
% function of N instead of defining it outside the loop as 0.
% something like: i = (N + 1) * 0.05;
% it won't improve performance nor save memory, its just more consice,
% and you don't need to move around the code to determine its value.
i=i+0.05;
%
% Real implementation goes here
%
E_nernst = sin(i);
V_out = exp(i);
% again, adding 1 to the current N, because indexing the zeroth
% position results in an error.
Q(N+1) = N_cells*i*(E_nernst - V_out);
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by