For loop not working

2 ビュー (過去 30 日間)
Leeba Ann Chacko
Leeba Ann Chacko 2022 年 6 月 6 日
コメント済み: Leeba Ann Chacko 2022 年 6 月 6 日
I have a 2x4 matrix called A. I would like to find the sum of each column and divide each element in that column with the sum of that column. However, when I run the loop, the first 3 columns have no values in them. How do I rectify this? The following is my code:
A = rand(2,4)
for i=length(A)
B(:,i) = A(:,i)./sum(A(:,1));
end

採用された回答

VBBV
VBBV 2022 年 6 月 6 日
編集済み: VBBV 2022 年 6 月 6 日
A = rand(2,4)
A = 2×4
0.9006 0.7820 0.6684 0.4557 0.2964 0.9567 0.3112 0.9163
for i=1:length(A) % using a single value
B(:,i) = A(:,i)./sum(A(:,i)); % divide each element with sum of that column
end
B
B = 2×4
0.7524 0.4498 0.6823 0.3322 0.2476 0.5502 0.3177 0.6678
It seems you are using a single value in loop counter
  2 件のコメント
VBBV
VBBV 2022 年 6 月 6 日
編集済み: VBBV 2022 年 6 月 6 日
if you want values for first 3 columns and rows, start with 1. you also need to update
sum(A(:,1)) % this is for 1st col only
with
sum(A(:,i) % corresponding column
Leeba Ann Chacko
Leeba Ann Chacko 2022 年 6 月 6 日
Thank you! I can't believe I missed that. :P

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by