フィルターのクリア

Use if / else inside a for-loop and change values of array depending on condition

7 ビュー (過去 30 日間)
ARP
ARP 2019 年 2 月 9 日
コメント済み: ARP 2019 年 2 月 9 日
Hi all,
I am stuck with the following step and I can't find the solution. The code I need is to change the columns of an array depending on the column index. For odd numbers, without change, for even numbers change the sign.
The size of the array should be variable by dimensions 1 and 2.
Here is what I tryied. Can someone help me please.
Thanks
Size_1 = 5;
Size_2 = 6;
array = ones(Size_1,Size_2);
for i=1:Size_2
if rem(i,2)==0
new_array_2 = array(:,i);
else
new_array_2 = -1*array(:,i);
end
end
new_array should be this
new_array =
1 -1 1 -1 1 -1
1 -1 1 -1 1 -1
1 -1 1 -1 1 -1
1 -1 1 -1 1 -1
1 -1 1 -1 1 -1

採用された回答

madhan ravi
madhan ravi 2019 年 2 月 9 日
No loops needed:
size1=5;
size2=6;
A=ones(size1,size2);
A(:,2:2:end)=-A(:,2:2:end)
  2 件のコメント
ARP
ARP 2019 年 2 月 9 日
Thanks!
I am still corious what I did wrong on my script. I will need to implement something like that later on. Specifically, to read if the folder number is even or uneven.
madhan ravi
madhan ravi 2019 年 2 月 9 日
See the answer below.
Reasons:
  • You forgot to preallocate new_array_2.
  • You forgot to index new_array_2.

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

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 2 月 9 日
If you insist loop then:
Size_1 = 5;
Size_2 = 6;
A = ones(Size_1,Size_2);
for i=1:Size_2
if rem(i,2)==0
A(:,i)=-A(:,i); % if even change the sign
else
A(:,i)=A(:,i);
end
end

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by