# Replace table elements in more than one row

28 ビュー (過去 30 日間)
Davindra Usov 2023 年 3 月 22 日
コメント済み: Davindra Usov 2023 年 3 月 23 日
Hi,
I have outputted a vector (V) which contains the row indices of elements in a table (T) that contain the string 'rpm'.
T has 3 columns and I initially set all of the elements in column 3 to zero. I now wish to replace all elements in column 3 that have these row indices (so only row 3 and row 7) with a value of 6. I have tried doing this but it doesn't work:
V = [3;7]; % row indices
for i = 1:numel(V)
T(V(i), 3) = repmat(6, numel(V), 1);
end
I get an error saying To assign to or create a variable in a table, the number of rows must match the height of the
table.
Thank you
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
VBBV 2023 年 3 月 23 日
T = table(zeros(7,1),zeros(7,1),zeros(7,1),zeros(7,1)) % your table
T = 7×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
V = [3;7]; % row indices
T(V, 3) = [repmat({6},numel(V),1)] % put the element in cell array when assigning
T = 7×4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0

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

### 採用された回答

Cameron 2023 年 3 月 22 日
You should look into how MATLAB does its indexing. You don't have to loop through the array to change a value. Just do it like this:
T = zeros(10,3); %i just picked 10 rows of data
indx = [3,7];
T(indx,3) = 6
T = 10×3
0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Davindra Usov 2023 年 3 月 23 日
thank you very much. This works perfectly. The others do as well, however I can only accept one answer

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

### その他の回答 (1 件)

Cris LaPierre 2023 年 3 月 22 日

You can, but the code you wrote is trying to replace a single element with a vector, hence the error message.
When you are trying to replace each element with the same value, you do not need to use repmat. Perhaps you are trying to do this?
tb = table(zeros(4,1))
tb = 4×1 table
Var1 ____ 0 0 0 0
tb.Var1([1 3]) = 6
tb = 4×1 table
Var1 ____ 6 0 6 0
% you could also use repmat if you want
tb.Var1([2 4]) = repmat(10,2,1)
tb = 4×1 table
Var1 ____ 6 10 6 10

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

### カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by