# I am trying to perform a simple operation FOR loop. I think I am not able to get the indexing right.

4 Ansichten (letzte 30 Tage)
Abhishek K Singh am 14 Mai 2024
%%I am trying to something which seems pretty eady, but I cant get it right.
t1 = [2 7 11 14 16];
t2 = [3 6 9 12 15 17 19];
t3 = [5 8 10 13 14 15 17 19];
%% why does not the following operation work
for i =1:3
di = 2*ti
end
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Torsten am 14 Mai 2024
Bearbeitet: Torsten am 15 Mai 2024
%% why does not the following operation work
Because the numbers 1,2 and 3 in t1, t2 and t3 are not indices you can loop over, but part of the three independent variable names t1, t2 and t3.
You can define a cell array with name t with three elements - then its possible to perform numerical operations on the different cell array elements of t:
t{1} = [2 7 11 14 16];
t{2} = [3 6 9 12 15 17 19];
t{3} = [5 8 10 13 14 15 17 19];
for i =1:3
d{i} = 2*t{i};
end
d
d = 1x3 cell array
{[4 14 22 28 32]} {[6 12 18 24 30 34 38]} {[10 16 20 26 28 30 34 38]}
or shorter
d = cellfun(@(x)2*x,t,'un',0)
d = 1x3 cell array
{[4 14 22 28 32]} {[6 12 18 24 30 34 38]} {[10 16 20 26 28 30 34 38]}
But cell arrays are mostly a bad thing to handle - in order to say what is best in your situation we must know how many such t-arrays exist and what you want to do with them.
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Abhishek K Singh am 15 Mai 2024
Thanks, Torsten!

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by