How to create an array using for loop?

3 ビュー (過去 30 日間)
Patrick
Patrick 2012 年 11 月 6 日
Im trying to create an array B where the values are natural logs of A if greater than 1. If value is less or equal to 1 then I want 39 to be added to these values.
A=[8 14 3;-13 1 42;-39 -8 15];
B=zeros(size(A));
for k=1:size(A,1);
l=1:size(A,2);
if (A(k,l))>1
B(k,l)=log(A(k,l));
else
B(k,l)=A(k,l)+39 ;
end;
end;
I'm not sure where I'm going wrong. Can you please help me? Thanks
  2 件のコメント
per isakson
per isakson 2012 年 11 月 6 日
Why do you think it goes wrong?
Patrick
Patrick 2012 年 11 月 7 日
Because the values should be the log of and all I get is just the sum of values A + 39.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2012 年 11 月 7 日
You have
l=1:size(A,2);
so in the line
if (A(k,l))>1
you are doing a vector test, equivalent to
if A(k,:)>1
which is equivalent to
if A(k,[1 2 3])>1
When you test a vector in an "if" statement, the result is considered true only if all of the sub-results are considered true, just as if all() had been wrapped around the test, like
if all(A(k,:) > 1)
as some of your A entries do not satisfy that condition, the test is false and the else portion is executed.
  2 件のコメント
Patrick
Patrick 2012 年 11 月 8 日
Sounds reasonable but how do I put >1 to make it actually work then?
Image Analyst
Image Analyst 2012 年 11 月 8 日
Instead of
l=1:size(A,2);
you'd have a for loop over l (bad variable name by the way):
for l = 1 : size(A, 2)

サインインしてコメントする。


Andrei Bobrov
Andrei Bobrov 2012 年 11 月 7 日
l = A > 1;
B = A;
B(l) = log(B(l));
B(~l) = B(~l) + 39;
  1 件のコメント
Jan
Jan 2012 年 11 月 7 日
編集済み: Jan 2012 年 11 月 7 日
Just to avoid confusions: The index is an lowercase "L", not a "1" (one).

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by