How to ignore negative indices or assign it to zero in a loop

6 ビュー (過去 30 日間)
MD JAHIDUL HAQUE KHAN
MD JAHIDUL HAQUE KHAN 2021 年 5 月 5 日
x=[1 2 -1 -3 -4]
h=[0 1 3]
n=length(x)
m=length(h)
y=zeros(n,m)
for i=1:n
for j=1:m
if i-j>0
y(i,j)=h(j)*x(i-j+1)
else
y(i,j)=0 % My problem is here to assign if the element x(i-j) does not exist return zero
%but it is ignoring all the element in the matrix that is (i-j)< zero
end
end
end
I have tried approach this problem by setting up a matrix, however i did not start loop from zero since it is same both way if i am right

採用された回答

Stephan
Stephan 2021 年 5 月 5 日
編集済み: Stephan 2021 年 5 月 5 日
It is not needed to make the elements zero - they are already, because you preallocated y with zeros:
x=[1 2 -1 -3 -4]
h=[0 1 3]
n=length(x)
m=length(h)
y=zeros(n,m)
for i=1:n
for j=1:m
if i-j>0
y(i,j)=h(j)*x(i-j+1)
end
end
end
gives:
% alot of stuff
% ...
y =
0 0 0
0 0 0
0 2 0
0 -1 6
0 -3 -3
  3 件のコメント
Stephan
Stephan 2021 年 5 月 5 日
use:
if i-j>=0
instead of
if i-j>0
MD JAHIDUL HAQUE KHAN
MD JAHIDUL HAQUE KHAN 2021 年 5 月 5 日
Thanks Stefan

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by