Generating array of data using for-end looping

2 次查看(过去 30 天)
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

采纳的回答

Paulo Silva
Paulo Silva 2011-4-16
result1=zeros(1,100);p=1; %create a vector to save the values and the index
for i=1:20
j(i)=10^((i-1)/2);
for l=1:5;
y(l)=j(i)+l/5*j(i)*sqrt(10);
result1(p)=y(l); p=p+1; %save current value and increment index
end
end
result1; %your vector with the values
I didn't check if the values are correct, just plot(result1) and it does look like something logarithmic
Edit: You can't use the logspace function but maybe you can steal the logspace code ;)
d1=0;d2=9.5;n=100;
result1 = (10).^ [d1+(0:n-2)*(d2-d1)/(floor(n)-1), d2];

更多回答(2 个)

Matt Fig
Matt Fig 2011-4-16
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
Andrei Bobrov 2011-4-16
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,[]);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by