How Can I vectorize the following codes?

for i=1:40, A(i,2); end
for j=1:100, x(j)=1/j; end
s=0; for k=1:100, s=s+rand; end
I think for the second one, it should be something like
j=1:100;x(j)=1/j; ?
can anyone help me?

답변 (1개)

Walter Roberson
Walter Roberson 2015년 9월 15일

0 개 추천

The first one
for i=1:40, A(i,2); end
can be vectorized as:
;
That is, it does not do anything, unless you count the checking to be sure that A(i,2) exists.
The second one is
x = 1 ./ (1:100);
or
j = 1:100; x = 1./j;
Or if you need to be strict about the possibility that x already exists and might be larger than 100 elements,
j = 1:100; x(j) = 1./j;
The third one is
s = sum(rand(1,100));

이 질문은 마감되었습니다.

태그

질문:

2015년 9월 15일

마감:

2021년 8월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by