How to overwrite part of a matrix by a function of the row number.

5 次查看(过去 30 天)
I want to overwrite part of a matrix by a function of the row number.
For example, let
M=rand(10,5) and the function of row number:
f(ROW)=ROW^2.
This function should apply in the range from 1:5 for all columns.
Thus the overwritten matrix N would have the following components
1 1 1 1 1
4 4 4 4 4
9 9 9 9 9
16 16 16 16 16
25 25 25 25 25
0.0620452213196326 0.533771951767000 0.526102465795561 0.337583864052045 0.0513318861123711
0.298243971887764 0.109154212042459 0.729709448223228 0.607865907262946 0.0728852990989761
0.0463512648981808 0.825808857855598 0.707253485315422 0.741254049502218 0.0885274596747204
0.505428142457703 0.338097718802172 0.781377051799277 0.104813241973500 0.798350864113952
0.761425886690113 0.293973053026484 0.287976975614171 0.127888379782995 0.943008139570703
ONLY the initial 5 rows are changed by the power of row number
and ALL columns were modified likewise.
I tried the following approach:
M=rand(10,5);
r=1:1:5;
f=r'.^2;
M(1:5,:)=f;
but did not work.
I hope someone know how to correct this command or to suggest something new.
Thank your for your help
Emerson

采纳的回答

Walter Roberson
Walter Roberson 2011-4-18
for r = 1:5
M(r,:) = r^2;
end

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2011-4-18
without loop for
r = 1:5;
M(r,:) = r.'.^2*ones(1,size(M,2))
  1 个评论
Emerson De Souza
Emerson De Souza 2011-4-18
Thank you Andrei,
your suggestion is definitely valid in particular if a loop
is not desired.
Have a nice day
Emerson

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by