Filter löschen
Filter löschen

Produce matrix with loop

1 Ansicht (letzte 30 Tage)
Tom
Tom am 26 Feb. 2011
Hi! I have a homework problem that I have difficulties with.
The problem is asking me to create a m by n matrix, using a function file, whose elements are going to be the sum of the index of each element. For exemple my first column would be A(1,1)=2 A(2,1)=3 A(3,1)=4 and so on.. I also must use the ''for'' loop. I tried to figure out how am I going to solve this problem before typing anything in my script file, so I thought that I could assign a matrix composed of ones, and of the dimensions of my outpout argument like U=ones(m,n) so my index variable ''k'' in my for loop could give the right value of each one after each pass, but I can't figure out hiow can I do that.. Can you give me a hint ?
Thanks!

Akzeptierte Antwort

Matt Fig
Matt Fig am 26 Feb. 2011
Most people on here will not just do a whole homework assignment for you. If you don't do any work, you will not learn. I will show you most of the solution, and I bet you can easily fill in the rest. Be sure to study it so you understand.
function A = elems_sum(m,n)
% Put help here.
for ii = 1:m
for jj = 1:n
A(ii,jj) = ??????;
end
end
  2 Kommentare
Tom
Tom am 26 Feb. 2011
I'm sorry If I went too fast on the ''ask'' button I didn't know until now how could I use a nested loop. But be assured that I tried to find a way to write my script using my references. But thank you very much for your time. If I understand, the two for statements indicates that for the first pass ii will equal 1, until all the values of jj are passed; so in my function the loop does (1+1),(1+2) etc.. until ii=m, then the loops ends and I have my matrix.. Thanks again..
Matt Fig
Matt Fig am 26 Feb. 2011
Sounds like you got it. Good luck to you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

chris hinkle
chris hinkle am 27 Feb. 2011
Here's an idea, tell your teacher not to promote for loops and take advantage of matlabs strength in vectorized functions
Matr=ones(m, n); [y,x] = find(Matr > 0); indMat = y+x;
The less you use for loops the better!
  2 Kommentare
Matt Fig
Matt Fig am 27 Feb. 2011
You could have just used find(Matr) without first doing the logical comparison. And I think you meant:
Matr=ones(m, n); [y,x] = find(Matr); Matr(:) = y+x
We can even do without using FIND all together:
A = cumsum([2:m+2;ones(n-2,m+1)])
chris hinkle
chris hinkle am 27 Feb. 2011
Good point matt, and yes I was just being sloppy just answered this on my phone!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by