for文とif 文

15 views (last 30 days)
sz
sz on 25 Oct 2021
Edited: Walter Roberson on 25 Oct 2021
現在100×3 の数字が1と0のみのデータがあります。
そこからif 文やfor 文を使って下記の計算をしたいです
1列目の数字がもし1だったら1×2 0だったら0×0
2列目の数字がもし1だったら1×2^2 0だったら0×0
3列目の数字がもし1だったら1×2^3  0だったら0×0
そしてその数字を足していっていただきたいです。
例)1、1、0の場合、1×2+1×2^2+0=6
これが100行分あるのでその計算をしていきたいので可能でしたらスクリプトを教えていただきたいです。
100×3のデータは下記のスクリプトのCになります。
よろしくお願いいたします。
rng(1,'philox')
X = randi([0 1], 3, 3, 100);
a = tril(ones(3), -1) == 1;
a = repmat(a, 1, 1, 100);
X(a) = 0;
X = X + permute(X,[2 1 3]);
a = eye(3) == 1;
a = repmat(a, 1, 1, 100);
X(a) = 1;
A = reshape(permute(X, [2 1 3]), 1, [], 100);
B = squeeze(A)';
C=B(:,[4,7,8]);
  1 Comment
Walter Roberson
Walter Roberson on 25 Oct 2021
Approximate translation:
Currently, there is data with only 1 and 0 numbers of 100x3.
From there, I want to do the following calculations using if and for statements
If the number in the first column is 1, it is 1x2. If it is 0, it is 0x0.
If the number in the second column is 1, 1x2 ^ 2. If it is 0, 0x0
If the number in the third column is 1, then 1x2 ^ 3; if it is 0, then 0x0
And I would like you to add those numbers.
Example)
In the case of 1, 1, 0, 1 × 2 + 1 × 2 ^ 2 + 0 = 6
Since this is for 100 lines, I would like to calculate it, so please tell me the script if possible.The 100x3 data will be C in the script below.
Thank you.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 25 Oct 2021
Edited: Walter Roberson on 25 Oct 2021
rng(1,'philox')
X = randi([0 1], 3, 3, 100);
a = tril(ones(3), -1) == 1;
a = repmat(a, 1, 1, 100);
X(a) = 0;
X = X + permute(X,[2 1 3]);
a = eye(3) == 1;
a = repmat(a, 1, 1, 100);
X(a) = 1;
A = reshape(permute(X, [2 1 3]), 1, [], 100);
B = squeeze(A)';
C=B(:,[4,7,8]);
C(1:5,:)
ans = 5×3
0 1 1 0 0 0 0 0 0 1 1 1 0 0 0
D = C * 2.^(1:3).'
D = 100×1
12 0 0 14 0 2 0 4 12 8

More Answers (0)

Community Treasure Hunt

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

Start Hunting!