Matrix from a for FOR loop with IF conditioning

1 回表示 (過去 30 日間)
Agent Cooper
Agent Cooper 2014 年 4 月 25 日
コメント済み: Jos (10584) 2014 年 4 月 25 日
I have the following problem:
A = [1 2 3; 4 5 6; 7 8 9]
for i = 1:n
if rem(i,2)== 0
x = fliplr(D(i,:))
else x = D(i,:)
end
B(i) = x
end
I'm trying to get the B matrix that should look like
B = [1 2 3; 6 5 4; 7 8 9]
but I get the following error message instead
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in back_and_forth (line 16)
B(i) = x
Could anyone help me with this?

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 4 月 25 日
編集済み: Azzi Abdelmalek 2014 年 4 月 25 日
A = [1 2 3; 4 5 6; 7 8 9]
A(2:2:end,:)=fliplr(A(2:2:end,:))
%Or if you want to do it with a for loop
A = [1 2 3; 4 5 6; 7 8 9]
n=size(A,1)
B=A;
for i = 1:n
if rem(i,2)== 0
B(i,:) = fliplr(A(i,:))
end
end

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2014 年 4 月 25 日
n = size(A,1)
...
B(i,:) = x
...
  1 件のコメント
Jos (10584)
Jos (10584) 2014 年 4 月 25 日
or using indexing alone
B = A ; % keep the original
B(2:2:end,:) = B(2:2:end,end:-1:1)

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


Geoff Hayes
Geoff Hayes 2014 年 4 月 25 日
Hi Chris,
I'm guessing that n should be 3 in this example, and that in the code D is set (at some point) with A.
So the problem is with your assignment, B(i)=x. You are assigning a single element of B to a row vector of three elements. This may be fine if B were defined to be a cell array (and you had written B{i}), but since you want it to be a matrix, then your assignment should mimic how you got x but in the opposite "direction".
Note that the assignment for x is x = D(i,:) or x = fliplr(D(i,:)). In either case you extract all columns (using the :) from the ith row of D. So when you assign this vector to B it should be the "same" - set all columns (using the :) of the ith row of B to x:
B(i,:) = x;
Note that to avoid the B is growing at each iteration warning, you could just initialize B at the beginning to:
B = zeros(size(D));
Hope that this helps!
Geoff

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by