How to get the result of Plus A1, A2, A3, A4, ..., A(i) using a loop?

3 ビュー (過去 30 日間)
HOON KIM
HOON KIM 2018 年 1 月 22 日
コメント済み: Snehal Patil 2020 年 4 月 18 日
I have multiple matrices with name of 'A' with sequent numbers (1, 2, 3, ..., (i)). So, I have these matrices.
A1 = [9,2,3,6]; A2 = [4,5,2,4]; A3 = [8,2,5,6]; . . . A(i) = [a,b,c,d];
And I want to see the result of all plus.
I want to see this.
Plus = [9+4+8+...+a, 9+...+b, 10+...+c, 16+...+d]
Could you make the loop command using for i = 1:number of A(i). Thank you so much.
  2 件のコメント
Stephen23
Stephen23 2018 年 1 月 22 日
編集済み: Stephen23 2018 年 1 月 22 日
"I have multiple matrices with name of 'A' with sequent numbers (1, 2, 3, ..., (i))"
That is exactly how beginners force themselves into writing slow, buggy, complex code that is hard to debug:
You should use indexing: indexing is neat, very efficient, and easy to debug. Not only that, if you had stored your data in one matrix then the final sum would be as simple and efficient as
sum(A)
Guillaume
Guillaume 2018 年 1 月 22 日
We cannot stress enough that "I have multiple matrices with name of 'A' with sequent numbers" is your biggest mistake and the cause of many problems to come.
Do not number variables. Any kind of sequential naming is a clear indication that you should only have one variable that you index.

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

回答 (1 件)

James Tursa
James Tursa 2018 年 1 月 22 日
The best answer is to not create variables with these names in the first place, because as you are finding out they are hard to deal with in a generic way downstream in your code. What you should be doing instead is either a matrix where each of your Ai is a row or column of the matrix, or maybe a cell array where A{i} would be used instead of Ai. Then it is easy to extract and sum whatever you want.
For your current situation, you could do something like this:
result = A1;
n = number of vectors to add
for k=2:n
result = result + eval(['A' num2str(k)]);
end
But suppose you had all of the Ai's as rows in a big matrix A. Then it would just be this:
result = sum(A);
See how much easier it is if you have your data stored in variables properly?
  1 件のコメント
Snehal Patil
Snehal Patil 2020 年 4 月 18 日
Thankyou so much,this was very helpful

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by