Reputation: 3405
I want to save a string with its corresponding index in a matrix but I am getting an error.
Here is a small example:
Mat_=[];
Val1=[10,19,22,15,30];
Val2=20
Strs_=[];
for i= 1:length(Val1)
if abs(Val1(1,i))<abs(Val2)
Str_={'Überschritten'};
else
Str_={'Unterschritten'};
end
Strs_=[Strs_;Str_];
Mat_=[Mat_;i];
end
Mat_
Strs_
FMat=[Mat_,Strs_]
Upvotes: 1
Views: 84
Reputation: 3640
You need a cell array to work with strings. To do this, you can preallocate a cell array and fill it.
Val1 = [10,19,22,15,30];
Val2 = 20;
FMat = cell(length(Val1), 2); % Preallocate empty cell array
for idx = 1:length(Val1)
if abs(Val1(1,idx)) < abs(Val2)
Str_ = 'Überschritten';
else
Str_ = 'Unterschritten';
end
FMat(idx, :) = {idx, Str_};
end
Your FMat
cell array will be:
1 'Überschritten'
2 'Überschritten'
3 'Unterschritten'
4 'Überschritten'
5 'Unterschritten'
Notice that I also changed your loop variable i
to idx
. In MATLAB, i
and j
are defined as sqrt(-1)
. It is always a good idea to give your variables other names.
Upvotes: 4