# MATLAB producing ans but wont upload variable, extremely strange behavior

조회 수: 1(최근 30일)
Robert Scott 2021년 7월 31일
댓글: Image Analyst 2021년 8월 1일
I am doing nothing special here but vectorizing an array
When i do something like the below code below matlab is going off, and producing an "ans" on the screen that has the correct values in it.
However, it is creating a completely empty variable called "test" despite the fact that i am setting that command to the variable test.
So i get the correct "ans" on the screen and an empty variable called test
What is going on here? I can click on "ans" in the workspace and see everything that should be there but test will be a variable of the same size but empty.
test = test1(1,1);test2(1,2)

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

### 채택된 답변

Image Analyst 2021년 7월 31일
편집: Image Analyst 2021년 7월 31일
Did you forget to enclose the vectors in brackets to form a matrix. See this:
test1 = rand(1,2);
test2 = rand(1,2);
test = test1(1,1); test2(1,2) % Two separate lines of code on the same line
test = [test1(1,1); test2(1,2)] % one line of code to stack the vectors on top of each other in a new matrix.
Did that produce a forehead-slapping moment?
##### 댓글 수: 14표시숨기기 이전 댓글 수: 13
Image Analyst 2021년 8월 1일
I was running it with join() to see how that differed from my two solutions and it appears that your input vectors area actually strings, not numerical, because join() only works with text.
So for completeness, I'm showing the two cases with different length vectors.
% Declare simple sample data.
test1 = [1,2,3,4];
test2 = [21,22,23,24,25,];
% For case 3, to use strrep, they must be strings, not numbers.
test1 = ["1","2","3","4"];
test2 = ["21","22","23","24", "25"];
% Case 2 : different lengths.
L1 = length(test1);
L2 = length(test2);
if L1 < L2
t1 = [test1, zeros(1, abs(L2-L1))]
t2 = test2
elseif L2 < L1
t1 = test1
t2 = [test2, zeros(1, abs(L2-L1))]
else
t1 = test1;
t2 = test2;
end
output2 = reshape([t1;t2], 1, [])
% Case 3: join - requires strings, not numbers.
% Create an array of 8 elements
test = [test1(:).', test2(:).']
% Make it a single string with spaces between, not an array.
test = join(test)
% Remove all spaces.
test = strrep(test,' ','')
You see:
output2 =
1×10 string array
"1" "21" "2" "22" "3" "23" "4" "24" "0" "25"
test =
1×9 string array
"1" "2" "3" "4" "21" "22" "23" "24" "25"
test =
"1 2 3 4 21 22 23 24 25"
test =
"12342122232425"
If I had known that you were dealing with text in advance, and if I had known what you wanted in advance, it would have gone much quicker with less back and forth. Note that I used simple data for the example that was not proprietary or secret so I would not get into trouble with my company over IP issues because of patents I'm working on.

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

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by