Generating array of data using for-end looping
Afficher commentaires plus anciens
I want to generate an array of number using for-end, i know that I can generate logarithmic series using logspace, but in this case, i can't use that
so I run this code:
function y=generate
for i=1:20
j(i)=10^((i-1)/2);
for l=1:5;
y(l)=j(i)+l/5*j(i)*sqrt(10);
end
end
result1=[y'];
my expectation is that I can generate logarithmic series of 100 number from 10^0 to 10^9.5, but instead getting 100 numbers, I run it and only get these:
ans =
1.0e+010 *
0.5162 0.7162 0.9162 1.1162 1.3162
then what should I do to get the 100 numbers, I need the '20' on 'i=1:20' in other function, that's why i can't use logspace because logspace can't be use inside looping command (for-end). Please I need your advice and I am just a beginner.
I appreciate your help
Réponse acceptée
Plus de réponses (2)
Matt Fig
le 16 Avr 2011
Another non-loop alternative (edit logspace):
mylogspace = @(x1,x2,n) 10.^ [x1+(0:n-2)*(x2-x1)/(n-1), x2]
mylogspace(0,9.5,100)
Here is how to do it in a loop:
function y = generate
cnt = 0;
y = zeros(1,100); % Pre-allocate
for ii = 1:19/99:20
cnt = cnt + 1;
y(cnt) = 10^((ii-1)/2);
end
Or in general:
function y = generate(x1,x2,n)
% Generates logspace(x1,x2,n)
cnt = 0;
y = zeros(1,n);
for ii = x1:(x2-x1)/(n-1):x2
cnt = cnt + 1;
y(cnt) = 10^ii;
end
Andrei Bobrov
le 16 Avr 2011
all without logspace
[jj,ll] = meshgrid(1:20,1:5);
result2 = reshape(10.^((jj-1)/2).*(1+ll/5*sqrt(10)),1,[]);
or
result2 = reshape(bsxfun(@(jj,ll)10.^((jj-1)/2).*(1+ll/5*sqrt(10)),1:20,(1:5)'),1,[]);
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!