Replacing 1 table cell value with a corresponding table cell value

I have a table of text characters of length M x N and a corresponding table of the same dimensions. in table 1, i want to replace all cells that contain a 'PXY7' with the corresponding value in Table 2.
For example if cell (A3,B5) in table 1 = 'PXY7' how do i replace this value with table 2's (A3,B5) value?

 採用された回答

Joel Miller
Joel Miller 2018 年 1 月 18 日

0 投票

This may not be the fastest method, but it works (I've replaced "PXY7' with 's'):
B1={'a';'s';'b'};
B2={'b';'s';'a'};
B3={'s';'a';'b'};
B4={'a';'b';'s'};
B5={'b';'a';'s'};
Table1=table(B1,B2,B3,B4,B5,'rownames',{'A1';'A2';'A3'});
D1={'1';'3';'2'};
D2={'3';'1';'2'};
D3={'1';'2';'3'};
D4={'3';'2';'1'};
D5={'3';'1';'2'};
Table2=table(D1,D2,D3,D4,D5,'rownames',{'C1';'C2';'C3'});
T1vars=Table1.Properties.VariableNames;
T2vars=Table2.Properties.VariableNames;
for k=1:length(T1vars)
T1index=ismember(Table1.(T1vars{k}),'s');
Table1.(T1vars{k})(T1index)=Table2.(T2vars{k})(T1index);
end

3 件のコメント

Matt Brianik
Matt Brianik 2018 年 1 月 18 日
Thanks but it needs to be done with a for loop so this code can be used as a template for handling different amounts of data from different spreadsheets with the same structure. so far I have this but whenever my loop switches columns, it goes down 1 in the row column, is there a way 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
%
Joel Miller
Joel Miller 2018 年 1 月 18 日
It is difficult to know where the problem lies, not knowing what IDX_IND is. Would you write IDX_IND out explicitly?
Matt Brianik
Matt Brianik 2018 年 1 月 18 日
here is the file i pulled it from, its just a test file, i think i figured out the issue though, thanks for your helkp

サインインしてコメントする。

その他の回答 (1 件)

Matt Brianik
Matt Brianik 2018 年 1 月 18 日

0 投票

Whenever this code runs it replaces values the way it should, but every time it moves over 1 column, it goes down 1 position in a row.
the results look like this
X B C
X Z C
X Z Y
A Z Y
A B Y
when they should look like
X Z Y
X Z Y
X Z Y
A B C
A B C

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by