how do I make a for loop go through another for loop?

1 次查看(过去 30 天)
Hi, I need to replace values of in a table with the values of another table indicated by a 3rd table wherever it =1.
I have this example here which is proceduraly identical to a problem i have where if I can make this work its a simple step of transforming my code.
Can anyone please help?
clear
close all
x= ['B';'A';'B';'A';'B'];
y= ['B';'B';'B';'B';'B'];
z= ['C';'B';'C';'C';'B'];
C1 = cellstr(x);
C2 = cellstr(y);
C3 = cellstr(z);
Initial_Table=[C1,C2,C3];
d= ['X';'X';'X';'X';'X'];
e= ['Z';'Z';'Z';'Z';'Z'];
f= ['Y';'Y';'Y';'Y';'Y'];
C1 = cellstr(d);
C2 = cellstr(e);
C3 = cellstr(f);
Mod_Table=[C1,C2,C3];
Original_Data_txt='For_Loop_Test.csv';
Mod_Data_txt='For_Loop_Test_Rep_Val.csv';
Original_Data = xlsread(Original_Data_txt);
IDX_IND = xlsread(Mod_Data_txt);
i=1;
j=1;
for x=1:5
for i=1:3
if IDX_IND(i,j)==1
strrep(Initial_Table(i,j),Mod_Table(i,j))
i=i+1;
end
end
end
  1 个评论
Rik
Rik 2018-1-18
You are using strrep with only two inputs, and you need 3. Also, you are incrementing i inside the loop, even though that is a loop index, while j remains unchanged. As a last point: is it on purpose that you are looping over x as well?
I feel all these loops could be reduced to a single loop at the most is you use clever indexing.

请先登录,再进行评论。

回答(1 个)

Matt Brianik
Matt Brianik 2018-1-18
You are right, ive been working on this a lot and actually was able to make the code look like
now its doing what i want, but after every indicie through a column it starts at a row 1 below the previous so my results look like this 'X' 'B' 'C' 'X' 'Z' 'B' 'X' 'Z' 'Y' 'A' 'Z' 'Y' 'B' 'B' 'Y'
instead of this 'X' 'Z' 'Y' 'X' 'Z' 'Y' 'X' 'Z' 'Y' 'A' 'B' 'C' 'A' 'B' 'C'
do you know how to fix this?
clear
close all
x= ['B';'A';'B';'A';'B'];
y= ['B';'B';'B';'B';'B'];
z= ['C';'B';'C';'C';'B'];
C1 = cellstr(x);
C2 = cellstr(y);
C3 = cellstr(z);
Initial_Table=[C1,C2,C3];
d= ['X';'X';'X';'X';'X'];
e= ['Z';'Z';'Z';'Z';'Z'];
f= ['Y';'Y';'Y';'Y';'Y'];
C1 = cellstr(d);
C2 = cellstr(e);
C3 = cellstr(f);
Mod_Table=[C1,C2,C3];
Original_Data_txt='For_Loop_Test.csv';
Mod_Data_txt='For_Loop_Test_Rep_Val.csv';
Original_Data = xlsread(Original_Data_txt);
IDX_IND = xlsread(Mod_Data_txt);
%
i=1;
j=1;
for i=1:3
for j=1:3 %(Or whatever is the highest numbered row of table)
if IDX_IND(i,j)==1
Initial_Table(i,j)=Mod_Table (i,j);
j=j+1;
end
i=i+1;
end
end

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by