MATLAB Answers

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

25 views (last 30 days)
ETHAN FROHNA on 15 Dec 2020
Commented: Stephen Cobeldick on 15 Dec 2020
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?

Answers (2)

SHIVAM KUMAR on 15 Dec 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.
Stephen Cobeldick
Stephen Cobeldick on 15 Dec 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)
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.

Sign in to comment.

SHIVAM KUMAR on 15 Dec 2020
You can make A as a vector
A=[[1 2 3 4];[5 6 7 8];[9 10 11 12]];
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

Community Treasure Hunt

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

Start Hunting!

Translated by