For loop in matlab
1 view (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
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
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.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!