Can anyone please explain the meaning of for m=1:size(x,1) & for n=1:size (x,2). in the program.please explain explicitly.
199 views (last 30 days)
Show older comments
x=[0,-1,4;9,-14,25;-34,49,64];
for m=1:size(x,1)
for n=1:size(x,2)
if x(m,n)>=0
B(m,n)=sqrt(x(m,n));
elseif x(m,n)<=0
B(m,n)= x(m,n)+50;
end
end
end
3 Comments
William Lucas
on 31 Jul 2016
I am a beginner in MatLab. This question and the answer is probably one of the most important things to grasp in learning MatLab which is my greatest struggle. But I cannot magically look at the answer and understand what is going on.
dpb
on 31 Jul 2016
I suggest you'll progress far more rapidly, then, if you'll just open
doc
and click on the "Getting Started" button and linearly work thru the sections on basic syntax, arrays, and such. Then, after that, when you come across some function with which you aren't yet acquainted, use the doc for it and just "'spearmint" at the keyboard and see what individual functions do with the input they're given...
Answers (2)
the cyclist
on 31 Jul 2016
Suppose x is a 3x4 matrix. Then size(x,1) will be equal to 3, and size(x,2) will be equal to 4. As dpb suggests, you can read more details on the documentation page for size.
0 Comments
Image Analyst
on 31 Jul 2016
Perhaps recode it like this to make it less cryptic:
x=[0,-1,4;9,-14,25;-34,49,64];
[rows, columns] = size(x);
for m=1:rows
for n=1:columns
this will process the array in the "slow" direction. Not that it matters for a small array like this but for megabyte sized 2-D arrays, do this:
x=[0,-1,4;9,-14,25;-34,49,64];
[rows, columns] = size(x);
for col = 1 : columns
for row = 1 : rows
Now the inner loop goes down rows first, which is the speedier way to process arrays.
I also renamed m and n to the more descriptive and easy to follow "row" and "col". Don't you hate it when you inherit code that looks like a cryptic alphabet soup on confusing 1 and 2 letter variable names? So do I.
0 Comments
See Also
Categories
Find more on Logical 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!