how to make a loop(for...end)
19 次查看(过去 30 天)
显示 更早的评论
I'm a new guy for matlab loop. Righi now I want to now some rools about loop(for...end). Such as how to make a loop to get all odd numbers from a matrix x=[1:100] or numbers like 1,5,9,13,17,21...? p.s.I know this x1=x(1:2:100) and x4=(1:4:100),but I want to know how to get it from a loop(for...end).
2 个评论
采纳的回答
Matt Fig
2011-3-22
It would be good if you learned to pre-allocate your vectors so your code runs efficiently...
.
.
.
EDIT In response to question about generalization.
The general case can be written:
N = 100; % The largest number. Change to whatever...
a = 1; % The starting point. Change to 3,5... whatever
n = zeros(1,ceil((N-a)/2)); % Pre-allocate the array...
for ii = 1:length(n)
n(ii) = 2*(ii)+(a-2);
end
9 个评论
Matt Fig
2011-3-22
Boy, you keep changing the problem! That is o.k., you will just have to realize that changing the problem changes the approach:
N = length(x); % The largest number. Change to whatever...
a = 1; % The starting point. Change to 3,5... whatever
S = 3;
n = zeros(1,floor((N-a)/(S))+1); % Pre-allocate the array...
for ii = 1:length(n)
n(ii) = x(S*(ii)+(a-S));
end
更多回答(3 个)
Paulo Silva
2011-3-22
clc
n={};
c=0;
for b=2:100
n1=[];
for a=b:2:100
n1=[n1 a];
end
c=c+1;
n{c,1}=n1;
end
The result is inside the n variable, n is a cell, each element of it contains the results n{1,1} gives you the odd numbers for 2:2:100, n{2,1} gives the odd numbers for 3:2:100 and so on...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!