Hi there i like to ask how can i get this into a for loop
x=rand(1,20)
h1=(x(2,1)-x(1,1));%First interval
h2=(x(3,1)-x(2,1)); %second interval
h3=(x(4,1)-x(4,1));%Third interval
h4=(x(5,1)-x(4,1));
I like the interval to run for another 20 times
i get it as
for i=1:20
h=( x(1,n) -x(1,(n-1)
iter=iter+1
end
Through this method, i can get 20 iterations but the h is remain the same value, can i know why and how can i change it to get the right way

댓글 수: 1

Jan
Jan 2021년 3월 18일
x = rand(1, 20)
h1 = x(2,1) - x(1,1); %First interval
This must fail: x has one row only, than x(2,1) does not exist. Please post some working code.

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

 채택된 답변

David Hill
David Hill 2021년 3월 18일

0 개 추천

x=rand(1,20);
for k=1:19
h(k)=x(k+1)-x(k);
end
Or without loop
x=rand(1,20);
h=diff(x);

댓글 수: 2

Mark Loui
Mark Loui 2021년 3월 18일
Hi thanks so much, i have another question
For example
x=rand(1,20);
for k=1:19
h(k)=x(k);
end
Can this be done?
As from what i seen it keeps getting the same output?
You do not need a loop to set h=x
x=rand(1,20);
h=x;%h is an array

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

추가 답변 (1개)

Jan
Jan 2021년 3월 18일
편집: Jan 2021년 3월 18일

0 개 추천

Why do you want a loop? It is working without a loop also - guessing that you mean x(1, 2) and not x(2, 1) as in the code in the question:
x = rand(20, 20)
h1 = x(:, 2) - x(:, 1); % First interval
h2 = x(:, 3) - x(:, 2); % second interval
h3 = x(:, 4) - x(:, 4); % Third interval
h4 = x(:, 5) - x(:, 4);

댓글 수: 3

Mark Loui
Mark Loui 2021년 3월 18일
편집: Jan 2021년 3월 18일
I like a loop the main question is y=rand(100,1)
I like to generate a for loop
for i=1:n-1
a(k)=y(k) %At each term i get one value extracted from the y
iter=iter+1
end
The extracted a(k) at different for each term is used later to find something else
Mark Loui
Mark Loui 2021년 3월 18일
Hi there i got it already thanks.
But i have another question, i like to create a diag function with a loop where the matrix is depending on the nxn size, how can i do it ?
After creating the element i like to fill in each of the element with a value, i am having trouble with this matter and not able to get the right approach, please help
Jan
Jan 2021년 3월 18일
What do you want your "diag function with a loop" to do? The explanation " matrix is depending on the nxn size" is not clear enough yet.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2020a

태그

질문:

2021년 3월 18일

댓글:

Jan
2021년 3월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by