A complicated matrix manipulation

1 回表示 (過去 30 日間)
J AI
J AI 2020 年 6 月 19 日
コメント済み: J AI 2020 年 6 月 19 日
So I have a matrix, let's say
A = [1 2;
1 0;
3 2;
0 1;
2 1;
1 2];
[r,c] = size(A);
In general, what I would like to do is:
for i = 1:r-1
x = A(6,1)*A(i,1) + A(6,2)*A(i,2);
end
However, here is the issue: if A(i,1) and/or A(i,2) is zero, and let's assume just A(i,1) is 0 and A(i,2) is non-zero, then, instead I would like to do:
x = A(6,1)*A(i-1,1) + A(6,2)*A(i,2);
And in case, even A(i-1,1) is also zero, then, I would like to do:
x = A(6,1)*A(i-2,1) + A(6,2)*A(i,2);
and so on and so forth (same for A(i,2)). Note, A(1,1), A(1,2), A(6,1), A(6,2) are always non-zeros. I am trying to get my head around it, but so far no luck, although it seems it should have a simple and efficient way.
Your help is highly appreciated. Please let me know if anything seems confusing.
Thanks in advance!
  2 件のコメント
Stephen23
Stephen23 2020 年 6 月 19 日
Your example matrix only has five rows, so none of your example code accessing its (non-existent) sixth row will work.
J AI
J AI 2020 年 6 月 19 日
it was a typo..i added anotther row. thanks for pointing out

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

採用された回答

Stephen23
Stephen23 2020 年 6 月 19 日
編集済み: Stephen23 2020 年 6 月 19 日
Try this reasonably "simple and efficient way":
r = size(A,1);
x = nan(r,1);
for k = 1:r
r1 = find(A(1:k,1),1,'last');
r2 = find(A(1:k,2),1,'last');
x(k) = A(6,1).*A(r1,1) + A(6,2).*A(r2,2);
end
  3 件のコメント
Stephen23
Stephen23 2020 年 6 月 19 日
編集済み: Stephen23 2020 年 6 月 19 日
'...generalizing it for "n" number of columns of A'
C = cumsum(A(:)~=0,1); % requires that first and last rows do not contain zeros!
B = nonzeros(A);
B = reshape(B(C),size(A));
x = sum(A(6,:).*B,2)
Personally I would just use a loop, as it makes the code intent much clearer.
J AI
J AI 2020 年 6 月 19 日
i agree for loops are clearer, but when you have a large-sized A with 10,000 columns, like i do, it is better getting the job done without a for loop. but as i said, i agree with you - in fact, i am not sure what's happening in the code you just provided so i will be figuring it out. thanks a lot man! really appreciate your help

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by