For loop in matlab

조회 수: 1 (최근 30일)
eli
eli 2014년 3월 7일
댓글: Image Analyst 2014년 3월 8일
Using for or while loops, and without using code in the form "for i=1:2:n or v(1,:)" so statements of the form "for i=1:n and v(1,n)" are okay,I need to write a function that takes a matrix input and a scalar input and returns a new matrix of elements every scalar apart.
For example a=function(magic(4),2) would return
a=[16 3; 9 6]
Anyone have an idea?

답변 (1개)

Image Analyst
Image Analyst 2014년 3월 7일
Hint:
newMatrix = m(startingIndexR:StepIndexR:endingIndexR, startingIndexC:StepIndexC:endingIndexC)
You can extract a matrix by giving a starting and ending index number and a step or increment value. You can do both rows (first index) and columns (second index) all in the same line of code. Define a function
function output = YourFunctionName(input1, input2)
% Your code goes here....
then do some code to assign "output" and call it from a main program like your homework problem stated.
  댓글 수: 2
eli
eli 2014년 3월 8일
Thanks for the reply I'm not allowed to index a matrix using double colon notation like in your hint "startingIndexR:StepIndexR:endingIndexR" I was able to complete the task using this notation
%retrieves every pixel factor apart from each row b=image(:,1:factor:end);
%retrieves every pixel factor apart from each column c=b(1:factor:end,:);
but now I have to use explicit for or while loops to rewrite this code., and I am really struggling with this.
Image Analyst
Image Analyst 2014년 3월 8일
What a ridiculous requirement. Here's the workaround for that nonsense:
for k = 1 : 20
if rem(k,2) == 0
continue;
end
k % Print k to command line
end
Now, in the loop assign your matrix. You might want to use a counter or else divide k by 2.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by