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

2 visualizzazioni (ultimi 30 giorni)
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?

Risposte (2)

SHIVAM KUMAR
SHIVAM KUMAR il 15 Dic 2020
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 Commenti
ETHAN FROHNA
ETHAN FROHNA il 15 Dic 2020
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 il 15 Dic 2020
"...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.

Accedi per commentare.


SHIVAM KUMAR
SHIVAM KUMAR il 15 Dic 2020
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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by