필터 지우기
필터 지우기

replacing a matrix in loop

조회 수: 5 (최근 30일)
HADIMARGO
HADIMARGO 2021년 6월 26일
답변: Stephen23 2021년 6월 26일
hi. i want to replace the matrix a in x(1,i) , when the x(1,i) == 0 and matrix b, when the x(1,i) == 1.
how could i do this?
clc; clear all; close all;
a = [ 1 1 1 0 0 0 ]
b = [ 0 0 0 1 1 1 ]
% Creating Random 0,1 in 10 times:
x = [ 1 1 0 0 ] % x has 4 column
for i=1:1:4
if x(1,i) == 0
x(1,i) = a;
elseif x(1,i) == 1
x(1,i) = b;
end
end
my code is wrong. how could i do this work? i know for example x(1,1) = 1 , how could i replace matrix with x(1,1)?
  댓글 수: 1
Jan
Jan 2021년 6월 26일
I do not understand, what you want to achieve.

댓글을 달려면 로그인하십시오.

답변 (2개)

Akshit Bagde
Akshit Bagde 2021년 6월 26일
편집: Akshit Bagde 2021년 6월 26일
Hi!
You won't be able to perform x(1,i) = a because the size of the left side is 1-by-1 and the size of the right side is 1-by-6.
You can try this!
a = [ 1 1 1 0 0 0 ];
b = [ 0 0 0 1 1 1 ];
x = [ 1 1 0 0 ];
% x has 4 Columns, a & b has 6 columns
for i=1:6:24
if x(i) == 0
x = [x(1:i-1) a x(i+1:end)]; % Replace x(i) with a
elseif x(i) == 1
x = [x(1:i-1) b x(i+1:end)]; % Replace x(i) with b
end
end

Stephen23
Stephen23 2021년 6월 26일
Do NOT use a loop for this! Do NOT expand any arrays inside loops!
A simpler and much more efficient approach using a comma-separated list:
a = [1,1,1,0,0,0];
b = [0,0,0,1,1,1];
x = [1,1,0,0];
c = {a,b};
z = [c{1+x}]
z = 1×24
0 0 0 1 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0
All MATLAB beginners need to learn how to use comma-separated lists effectively:
so that they can learn how to write simple and efficient MATLAB code.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by