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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by