How can i save the variabels values as array form in for loop?
1 view (last 30 days)
Show older comments
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'
Answers (1)
TADA
on 22 May 2022
Edited: TADA
on 22 May 2022
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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!