본문 바로가기
유용한 지식/Matlab

Using the Matlab 'for Statement' | Loop Statement

by 그래도_明 2020. 9. 24.

Using the Matlab 'for Statement' | Loop Statement

One of the most confusing things about using various computer languages is the 'for statement.'

Each language has different forms, so I search every time I write it.

I just wrote down for example, so I hope you can freely scrape and correct it.

%% Setting
a = zeros(1,10); 		% make that variable a is 1X10 matrix.

%% for loop
for i = 1:length(a) 			% i is from 1 to 10, and is executed repeatedly.
	if rem(i,2) == 0	% if i is even number,
		a(i) = 1;	% 1 is inserted in i^th of a.
    else			% else,
   		a(i) = -1;	% -1 is inserted in i^th of a.
    end
end

<Code Execution Results>

To give a brief description of the code, it is a code for adding -1 to a variable of size 1X10 and -1 to an odd number and 1 to an even number.

The rem function in the if statement makes the rest of i÷2 as a function that obtains the rest. It can be replaced by mod function.

For a detailed description of the if statement, see the post below.

2020/09/24 - [유용한 지식/Matlab] - Using Matlab 'if Statement' | Assumption Statement

 

Using Matlab 'if Statement' | Assumption Statement

Using Matlab 'if Statement' | Assumption Statement 'If statement' is confusing each time it is written because the rules vary depending on all programming languages. I'll leave you an example for th..

ev-engineer-student.tistory.com

----

%% Setting 
a = zeros(1,10);  % make that variable a is 1X10 matrix. 

%% for loop 
for i = 1:length(a)  % i is from 1 to 10, and is executed repeatedly. 
if rem(i,2) == 0 % if i is even number, 
a(i) = 1; % 1 is inserted in i^th of a. 
    else % else, 
    a(i) = -1; % -1 is inserted in i^th of a. 
    end 
end

----

반응형

댓글