how to insert a value into the array in a consistent manner.
    조회 수: 7 (최근 30일)
  
       이전 댓글 표시
    
If I want to get [0;1;1;1] when A=ones(3,1)=[1;1;1], I can get  [0;1;1;1] by typing [0;A].
If I want to get [0 1 1 1] when A=ones(1,3)=[1 1 1], I can get  [0 1 1 1] by typing [0 A].
How can I write them in the consistent way? Must I always use semicolon or space(or comma) dependign on whether A is a row vector or a column vector? 
댓글 수: 1
  Stephen23
      
      
 2019년 11월 20일
				
      편집: Stephen23
      
      
 2019년 11월 20일
  
			"Must I always use semicolon or space(or comma) dependign on whether A is a row vector or a column vector? "
If you want to use the concatenation operator [] then a comma/space or semi-colon is required.
"How can I write them in the consistent way?"
What does "consistent" mean? In one case you are adding a new row, in the other case a new column: do you expect to be able to use the same syntax for both of these?
채택된 답변
추가 답변 (1개)
  Bhaskar R
      
 2019년 11월 20일
        Are you asking for this ?
A = ones(3, 1);
if (size(A,2)>1)
    A = [0 A];
else
    A = [0;A];
end
댓글 수: 2
  Steven Lord
    
      
 2019년 11월 20일
				To make this code a little clearer, you might want to use the isrow or iscolumn function instead of explicitly checking the size. These will also return false if the input is not a vector.
A = ones(3, 2);
if (size(A,2)>1)
    A = [0 A]; % Error
else
    A = [0;A];
end
With isrow and iscolumn:
A = ones(3, 2);
if isrow(A)
    A = [0 A];
elseif iscolumn(A)
    A = [0; A];
else
    disp('A is not a vector')
end
Alternately, instead of using 0 use zeros to make a matrix with the appropriate number of rows or columns to be compatible with A. If you do that, you'd need to use some other criterion to determine whether to concatenate horizontally or vertically.
A = ones(3, 2);
B = [zeros(size(A, 1), 1), A]
C = [zeros(1, size(A, 2)); A]
  Bhaskar R
      
 2019년 11월 20일
				Yeah, I have been learning/growing with new commands, ways and techniques as a new contributer in this forum. Thanks for the feedback of the answer. Its my pleasure.!! 
참고 항목
카테고리
				Help Center 및 File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



