Filter löschen
Filter löschen

assigning values to an array that already has values

1 Ansicht (letzte 30 Tage)
Raul Castillo
Raul Castillo am 28 Okt. 2019
Kommentiert: ME am 29 Okt. 2019
so for example my array lets say s= [1 4 2 3 4 1 4 2 3 4 ]
and i want to assign 1=20 2=30 3=50 4=80 so that my new array would now be [20 80 30 50 80 20 80 30 50 80] how would i do this using loops?

Akzeptierte Antwort

ME
ME am 28 Okt. 2019
Totally not an elegant answer but you could use something like:
for i=1:numel(s)
if(s(i)==1)
s(i)==20;
elseif(s(i)==2)
s(i)==30;
elseif(s(i)==3)
s(i)==50;
elseif(s(i)==4)
s(i)==80;
end
end
This would then leave anything other than 1, 2, 3 and 4 unchanged.
As I say, it’s not elegant but it might give you enough of a start.
  3 Kommentare
Raul Castillo
Raul Castillo am 28 Okt. 2019
i do not know if i am doing it correctly the output is coming back as ans = logical 0
ME
ME am 29 Okt. 2019
Apolgies this was my fault. There should not be "==" in the commands to swap to the updated values, i.e. the code should be:
for i=1:numel(s)
if(s(i)==1)
s(i)=20;
elseif(s(i)==2)
s(i)=30;
elseif(s(i)==3)
s(i)=50;
elseif(s(i)==4)
s(i)=80;
end
end

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

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

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by