フィルターのクリア

How can I use a loop to input different arrays into the same equation so I do not have to repeat code?

1 回表示 (過去 30 日間)
I am trying to multipy three different arrays by 3 but I do not want to simply multiply them each by three, so is there a way I can use a for or loop function to do the multiplication for me for all three arrays?

回答 (2 件)

SHIVAM KUMAR
SHIVAM KUMAR 2020 年 12 月 15 日
Don't know why you want to use a loop for that .
for i=1:3
Arr[i,:]=Arr[i,:]*3; %That's only useful if you have a vector.
% For arrays its not much useful to do in a loop.
end
  3 件のコメント
ETHAN FROHNA
ETHAN FROHNA 2020 年 12 月 15 日
Sorry if that was confusing, this is what I am trying to accomplish:
A=[1 2 3 4]
B=[5 6 7 8]
C=[9 10 11 12]
So I am trying to multiply the three of these by without have to write
A*3
B*3
C*3
I am doing a much more complex problem for a homework but I want to know if there is a basic functions to multiplty them all by three at once.
Stephen23
Stephen23 2020 年 12 月 15 日
"...but I want to know if there is a basic functions to multiplty them all by three at once."
If you really want to multiply them "at once" then simply put all of the data into one numeric array (which could be a 3D array) and perform one multiplication.
If you want to keep them as separate arrays then simply store them all in one cell array (which they should be anyway) and use a basic loop:
C = {[1,2,3,4],[5,6,7,8],[9,10,11,12]};
for k = 1:numel(C)
C{k}*3
end
Defining the arrays in lots of separate variables is a mistake that will force you into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug. Indexing is much simpler and much more efficient.

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


SHIVAM KUMAR
SHIVAM KUMAR 2020 年 12 月 15 日
You can make A as a vector
A=[[1 2 3 4];[5 6 7 8];[9 10 11 12]];
A=A*3;
To use A or B or C we can use
A(1,:) %To use as A
A(2,:)%can be used as B
A(3,:)%Will work like C

カテゴリ

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