Inserting 0s in rows of an array

2 ビュー (過去 30 日間)
Alberto Acri
Alberto Acri 2023 年 7 月 18 日
コメント済み: Dyuman Joshi 2023 年 7 月 18 日
Hi. I have a matrix A1 and a vector B1.
If I have a 0 in any row of vector B1, I need to insert 0s in that same row of matrix A (see picture).
With this code the 0s are applied only to the first row of A. How come?
A1 = importdata("A1.mat");
B1 = importdata("B1.mat");
rows_B1 = height(B1);
for C = 1:height(rows_B1)
if B1(C) == 0
t1 = 0;
t2 = 0;
A1(C,1) = t1;
A1(C,2) = t2;
end
end

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 7 月 18 日
編集済み: Dyuman Joshi 2023 年 7 月 18 日
"With this code the 0s are applied only to the first row of A. How come?"
In your code, you have already defined rows_B1 to be the height of B1. That will return a scalar value.
rows_B1 = height(B1);
When you use height on rows_B1, it will just return 1 (because it is a scalar), and your loop will go from 1 to 1 i.e. only the 1st row.
for C = 1:height(rows_B1)
Correct your code as follows -
%Corrected
for C = 1:rows_B1
A better approach would be indexing -
%Sample data
A1 = [309 126; 310 126; 289 309; 209 309;291 309];
B1 = uint8([0 0 68 70 72])';
%Comparing values of B1 to 0
idx = B1==0
idx = 5×1 logical array
1 1 0 0 0
%Assigning all columns of corresponding rows to be 0
A1(idx,:) = 0
A1 = 5×2
0 0 0 0 289 309 209 309 291 309
  2 件のコメント
Alberto Acri
Alberto Acri 2023 年 7 月 18 日
Thanks! Could I also ask you how to modify the created A1 matrix so that the rows containing 0s are removed? For example, using: A1_n = A1(A1~=0) and the result is:
A1 = [289 309; 209 309;291 309];
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 18 日
%Sample data
A1 = [309 126; 310 126; 289 309; 209 309;291 309];
B1 = uint8([0 0 68 70 72])';
%Comparing values of B1 to 0
idx = B1==0
idx = 5×1 logical array
1 1 0 0 0
%Assigning all columns of corresponding rows to be 0
A1(idx,:) = 0
A1 = 5×2
0 0 0 0 289 309 209 309 291 309
%Removing the rows where rows in A are zeros is same as
%getting the rows where B1 is not equal to zero
A1_n = A1(~idx,:)
A1_n = 3×2
289 309 209 309 291 309

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by