How to take Matrix as arguments in user defined function?

조회 수: 2 (최근 30일)
Md. Abul Hayat
Md. Abul Hayat 2013년 11월 24일
편집: dpb 2013년 11월 24일
I am trying yo write a function that takes matrix as argument and returns a matrix.
function B=rpt(A))
j=length(A);
for i=1:j
B(2*i,:)=A(i,:);
B((2*i)-1,:)=A(i,:);
end
But It doesn't work. Can anyone explain why?
  댓글 수: 2
Azzi Abdelmalek
Azzi Abdelmalek 2013년 11월 24일
편집: Azzi Abdelmalek 2013년 11월 24일
What "it doesn't work" means? is there any error messages? And please give an example that allows to test your code, you can also explain what is the expected result
dpb
dpb 2013년 11월 24일
편집: dpb 2013년 11월 24일
More specifically, as written your function
a) Doesn't check which dimension is the greater but uses result of length() on the input argument as the size of the first dimension. Use
size(A,1)
instead. Depending on the input this won't matter but if you pass an array w/ more columns than rows it will error on a range error.
b) While not fatal, it doesn't preallocate B so the overhead in building B will be sizable as it reallocates over and over the new rows. Use
B=zeros(2*j,size(A,2));
before the loop
C) Stylistically, and occasionally the cause of actual errors or debugging grief, i and j are predefined in Matlab as the imaginaries of the same name in common mathematical use. Just be aware if complex variables are ever around of aliasing same.

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

답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by