필터 지우기
필터 지우기

Setting up vector function

조회 수: 2 (최근 30일)
K O
K O 2017년 11월 9일
편집: K O 2017년 11월 10일
I write a function SetUp to set up three vectors from an input vector k. Vector c = (-k(2); -k(3); ..... -k(n)) where I have n-1 elements. Vector d = (k(1)+k(2); k(2)+k(3); ...... k(n-1)+k(n); k(n)) where there are n elements And vector e = vector c.
Here is the code I wrote:
function [c,e,d] = SetUp
k = input('Enter k vector');
n = size(k,2);
for k1 = 1:n
c = -k(k1)*ones(n-1,1);
d = (k(k1)+k(k1+1))*ones(n,1); d(n) = k(n);
e = c;
end
end
By running this code I get an error: Index exceeds matrix dimensions.
Problem is in this line: d = (k(k1)+k(k1+1))*ones(n,1); d(n) = k(n);
In my opinion the problem is in indexing as the last term when Matlab runs d = (k(k1)+k(k1+1))*ones(n,1); is d = k(n)+k(n+1), where the program does not recognize k(n+1) as there is no such term in vector k.
So, the question is, how to overcome this problem as I don't even need the last term as the last term is d(n) = k(n)???
Thanks in advance!
  댓글 수: 1
Guillaume
Guillaume 2017년 11월 9일
You have to ask yourself several questions:
  • What is the purpose of the loop in your code? Note that at each iteration, you're completely overwriting the previous value of c, d and e.
  • Is a loop required to do what you want? (Hint: No)
  • How can you have a different equation for the last term? (Hint: calculate all the other terms from 1 to n-1 instead of up to n)
  • What happens with your code if the user enters a column vector instead of a row vector? (Hint: use numel instead of size(x, 2))

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

채택된 답변

Eric
Eric 2017년 11월 9일
편집: Eric 2017년 11월 9일
In your for loop, you are using k(k1+1). if k1 is the last element of k, then k(k1+1) will be exceeding the dimension of k. If you dont care about the last term, use
for k1 = 1:n-1
... Stuff ...
end
d(n) = k(n);
or if you need the other vectors to go to n, stick it in a conditional
for k1 = 1:n
... Other Stuff ...
if k1~=n
d = (k(k1)+k(k1+1))*ones(n,1);
end
end
  댓글 수: 1
K O
K O 2017년 11월 9일
I see what I was missing.
if k1~=n
d = (k(k1)+k(k1+1))*ones(n,1);
end
Thanks man!

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

추가 답변 (1개)

KL
KL 2017년 11월 9일
편집: KL 2017년 11월 9일
c = -k(2:end); %EDITED
d = k+[k(2:end);0];
e = c;
in case, k is row vector,
c = -k(2:end); %EDITED
d = k+[k(2:end),0];
e = c
that's all you need. No need for a loop!
  댓글 수: 3
K O
K O 2017년 11월 9일
I'll try without the for loop too.
Ty KL and Eric for discussion.
KL
KL 2017년 11월 9일
Bam! I totally overlooked it! Thanks, I'll edit the answer.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by