how to make a loop(for...end)

조회 수: 21 (최근 30일)
Tian Lin
Tian Lin 2011년 3월 22일
댓글: Walter Roberson 2021년 4월 5일
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
Nahla Mohsen
Nahla Mohsen 2021년 4월 5일
Write a program to find and print the value of A such that A=1+1/2+1/3+….+1/n

댓글을 달려면 로그인하십시오.

채택된 답변

Matt Fig
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
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
Tian Lin
Tian Lin 2011년 3월 22일
man,that's cool,I only need to change S and a to get the best result.Thank you very much.I believe some day I can write the code by myself,like you.

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Paulo Silva
Paulo Silva 2011년 3월 22일
n=[];
for a=1:2:100
n=[n a];
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 3월 22일
for K = 1:100
a = K:2:100;
%here, do something with the vector "a"
end
Tian Lin
Tian Lin 2011년 3월 22일
if I have numbers larger than 100,just like 10000,whether I will write 10000 "for"?

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2011년 3월 22일
Please don't do that: please read this FAQ instead.

Paulo Silva
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...
  댓글 수: 1
Tian Lin
Tian Lin 2011년 3월 22일
thank you Paulo.It's hard to me to understand something like reduce using memory.Also,I don't know the cell very much,so I find Matt's code much esaier.whatever,thanks a lot.

댓글을 달려면 로그인하십시오.

카테고리

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