Filter löschen
Filter löschen

Assigning a variable to equal another in a for loop

4 Ansichten (letzte 30 Tage)
Angus
Angus am 25 Jul. 2013
This is a simplified version of the problem I'm experiencing in my code to illustrate what I want to achieve.
Ele1 = [1 2 3 4 5 6 7 8 9 10];
Ele2 = [11 12 13 14 15 16 17 18 19 20];
Ele3 = [21 22 23 24 25 26 27 28 29 30];
for E=1:3;
Col1Name = ['Ele' num2str(E) 'Column1'];
Col2Name = ['Ele' num2str(E) 'Column2'];
NameEle = ['Ele' num2str(E)];
Ele = [NameEle];
a = 1;
for Col=2:2:10;
Column1(a)=Ele(Col-1);
Column2(a)=Ele(Col);
a = a+1;
end
assignin('base', Col1Name, Column1);
assignin('base', Col2Name, Column1);
end
I want an output of;
Ele1Column1 = [1 3 5 7 9]
Ele1Column2 = [2 4 6 8 10]
Ele2Column1 = [11 13 15 17 19]
Ele2Column2 = [12 14 16 18 20]
Ele3Column1 = [21 23 25 27 29]
Ele3Column2 = [22 24 26 28 30]
But the line "Ele = [NameEle];" doesn't assign Ele to the value of Ele1, Ele2 or Ele3, so it can't be accessed in the inner for loop. My question is to see whether there is a command that I can use that makes Ele = Ele1 without actually typing that in (as that defeats the purpose of the for loop). [Note this is a simplified example of what I'm using it for, if I could perform this function in my actual code it would save a lot of time]. Thank you

Antworten (2)

David Sanchez
David Sanchez am 25 Jul. 2013
Hi, I made some changes to your code, here you are:
Ele = cell(3,1);
Ele{1} = [1 2 3 4 5 6 7 8 9 10];
Ele{2} = [11 12 13 14 15 16 17 18 19 20];
Ele{3} = [21 22 23 24 25 26 27 28 29 30];
for E=1:3;
Col1Name = ['Ele' num2str(E) 'Column1'];
Col2Name = ['Ele' num2str(E) 'Column2'];
tmp_array = Ele{E};
odd_terms = 1:2:length(tmp_array);
odd_array = tmp_array(odd_terms);
even_terms = 2:2:length(tmp_array);
even_array = tmp_array(even_terms);
assignin('base', Col1Name, odd_array);
assignin('base', Col2Name, even_array);
end

Andrei Bobrov
Andrei Bobrov am 25 Jul. 2013
Ele = bsxfun(@plus,(0:10:20)',1:10);
EleColumn = permute(reshape(Ele,size(Ele,1),2,[]),[1 3 2]);

Kategorien

Mehr zu Programming 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