For loop in matlab

1 view (last 30 days)
eli
eli on 7 Mar 2014
Commented: Image Analyst on 8 Mar 2014
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?

Answers (1)

Image Analyst
Image Analyst on 7 Mar 2014
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 Comments
eli
eli on 8 Mar 2014
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 on 8 Mar 2014
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!