How to use the 'if' statement in matlab? - matlab

I have a cell array of size 5x5 as below
B= 00 10 11 10 11
01 01 01 01 11
10 00 01 00 01
10 10 01 01 11
10 10 10 00 10
And two column vectors
S1= 21
23
28
25
43
S2= 96
85
78
65
76
I want to create a new cell array of the same size as B say 5x5 such that it satisfies the following condition
Final={S1 if B{i}=11
S1 if B{i}=10
S2 if B{i}=01
S2 if B{i}=00
So the resulting output would be something like this
Z = s2 s1 s1 s1 s1
s2 s2 s2 s2 s1
s1 s2 s2 s2 s2
s1 s1 s2 s2 s1
s1 s1 s1 s2 s1
ie Z= 96 21 21 21 21
85 85 85 85 23
28 78 78 78 78
25 25 65 65 25
43 43 43 76 43
I tried using the if condition but i get error saying
'Error: The expression to the left of the equals sign is not a valid target for an assignment.'
for i=1:1:128
for j=1:1:16
if fs{i,j}=00
Z{i,j}=S1{i,j}
elseif fs{i,j}= 01
Z{i,j}=S2{i,j}
elseif fs{i,j}= 10
Z{i,j}=S1{i,j}
elseif fs{i,j}= 11
Z{i,j}=S2{i,j}
end
end
I think I'm making a mistake in the if statement as well as the expressions I'm using. Where am i going wrong? Please help thanks in advance.

Use == for comparison and = for assignment. So if fs{i,j}==00, etc.
Edit: Matlab is really designed for highly vectorized operations. Nested loops are slow compared to native functions, and typically can be replaced with vectorized versions. Is there any particular reason why you are using cell arrays instead of matrices, especially when you only have numeric data?
If B, S1, and S2 were matrices your code could be written in one highly efficient line that will run much much faster:
Z = bsxfun(#times, S1, B == 11 | B == 10) + bsxfun(#times, S2, B == 01 | B == 0)

Since B is a cell array you will want to convert it to a matrix using cell2mat unless you'd like to use cellfun.
Instead, you can just call B_mat = cell2mat(B), followed by (B_mat>=10).*repmat(S1,1,5) + (B_mat<10).*repmat(S2,1,5).
It's possible that your cell array actually contains binary values, possibly represented as strings, in which case the conditions used above would need to be changed. Then using cellfun may be necessary.

Related

Shifting Index values in matlab

Suppose I have two rows as follows with the data
R1 = 12 13 15 17 200 23
R2 = 32 22 43 67 21 74
I would like to know how to shift the values of the 2nd index and 3rd index of R1 (e.g, 13 15) into the second row of R2 so it becomes
R2 = 32 13 15 67 21 74
It's very simple: R2(2:3) = R1(2:3);
Code sample:
R1 = [12 13 15 17 200 23];
R2 = [32 22 43 67 21 74];
R2(2:3) = R1(2:3);
You can also use the following: R2([2,3]) = R1([2,3]);, in case indexes are not sequential.
In case R1 and R2 are two rows in a matrix, you can use the following sample:
% Create the input matrix A:
R1 = [12 13 15 17 200 23];
R2 = [32 22 43 67 21 74];
A = [R1; R2];
%Copy values from index 2 and 3 of first row to index 2 and 3 of second row:
A(2, [2,3]) = A(1, [2,3]);
In case there are more rows, and you need to "shift" all down, you can use the following example:
%Create sample matrix A (6x6 elements).
A = magic(6);
%"Shift" values of index 2,3 of all rows, one row down:
A(2:end, [2,3]) = A(1:end-1, [2,3]);
Refer here: http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

Create new variable that recognizes changes in a code in Matlab

I have a double matrix B that has in C1 the year 1998 and in C2 a code (unrepeated). Each C2 is given a value in C3.
% C1 C2 C3
B=[ 1998 22 37
1998 34 7
1998 76 12
1998 98 29
1998 107 14
…]
This is how I got to B:
N1=[N{:,1} N{:,2} N{:,3}];
N1=unique(N1(:,1:3),'rows');
N3= unique(N1(:,1:2),'rows');
for m=1:size(N3,1)
N3(m,3)=sum(N1(:,1) == N3(m,1) & N1(:,2)==N3(m,2));
end
B=N3((N3(:,1) == 1998),:);
I have a cell-array A with the years horizontally disposed in R1, un-repeated values in Y, and corresponding codes in the columns that follow. The codes match the ones in C2 from variable B.
A={Y 1996 1997 1998 1999 %R1
1 107 107 22 22
13 98 98 76 1267
… }
Is there a way I could get a new variable that recognizes the change in the codes in variable A, and presents the corresponding values from C3 in B? For instance:
AB={Y Initial C2 Change C2
1 107 14 22 37
13 98 29 76 12 }
AB = {'Y' 'Initial' 'C2' 'Change' 'C2'}; % initialize result cell array
for i=2:size(A,1) % loop through rows of A
indicesOfChanges = find(diff([A{i,2:end}])); % find changes in row
for j=1:length(indicesOfChanges) % for all changes look up the corresponding values
ind1=find(B(:,2)==A{i,indicesOfChanges(j)+1}); % row index in B of value before change
ind2=find(B(:,2)==A{i,indicesOfChanges(j)+2}); % row index in B of value after change
AB{end+1,1} = A{i,1};
AB{end,2} = B(ind1,2);
AB{end,3} = B(ind1,3);
AB{end,4} = B(ind2,2);
AB{end,5} = B(ind2,3);
end
end
Maybe this could be further improved by using a vectorized approach, but as long as your arrays aren't too big it should work fast enough using loops.

lookup columns and match in matlab

I have an excel_1 with 4 columns (A, B, C, score) with different combinations. I have another excel_2 with 3 columns (A, B, C). I would like according A, B, C and find out score. I'm trying using excel index and match function, but i still can not figure out. without coding, it really make me trouble to match it one by one...May i know how to write code in Matlab?
Example:
excel_1
99 5 35 12
99 2 32 14
97 5 13 94
...
excel_2
97 5 13
99 2 32
...
After execute the code,
Result:
excel_2
97 5 13 94
99 2 32 14
...
Thanks a lot...
A = xlsread('excel_1.xlsx');
B = xlsread('excel_2.xlsx');
[~,J] = ismember(B,A(:,1:size(B,2)),'rows');
if any(J)
result = A(J,:);
end
??? Subscript indices must either be real positive integers or logicals.
Error in ==> Untitled at 6
result = A(J,:);
Solved. can not exist impossible between B and A.
May be you can try this.
[~,J] = ismember(excel_2,excel_1(:,1:size(excel_2,2)),'rows');
if any(J)
result = excel_1(J,:);
end
Then
result =
97 5 13 94
99 2 32 14

How do I select n elements of a sequence in windows of m ? (matlab)

Quick MATLAB question.
What would be the best/most efficient way to select a certain number of elements, 'n' in windows of 'm'. In other words, I want to select the first 50 elements of a sequence, then elements 10-60, then elements 20-70 ect.
Right now, my sequence is in vector format(but this can easily be changed).
EDIT:
The sequences that I am dealing with are too long to be stored in my RAM. I need to be able to create the windows, and then call upon the window that I want to analyze/preform another command on.
Do you have enough RAM to store a 50-by-nWindow array in memory? In that case, you can generate your windows in one go, and then apply your processing on each column
%# idxMatrix has 1:50 in first col, 11:60 in second col etc
idxMatrix = bsxfun(#plus,(1:50)',0:10:length(yourVector)-50); %'#
%# reshapedData is a 50-by-numberOfWindows array
reshapedData = yourVector(idxMatrix);
%# now you can do processing on each column, e.g.
maximumOfEachWindow = max(reshapedData,[],1);
To complement Kerrek's answer: if you want to do it in a loop, you can use something like
n = 50
m = 10;
for i=1:m:length(v)
w = v(i:i+n);
% Do something with w
end
There's a slight issue with the description of your problem. You say that you want "to select the first 50 elements of a sequence, then elements 10-60..."; however, this would translate to selecting elements:
1-50
10-60
20-70
etc.
That first sequence should be 0-10 to fit the pattern which of course in MATLAB would not make sense since arrays use one-indexing. To address this, the algorithm below uses a variable called startIndex to indicate which element to start the sequence sampling from.
You could accomplish this in a vectorized way by constructing an index array. Create a vector consisting of the starting indices of each sequence. For reuse sake, I put the length of the sequence, the step size between sequence starts, and the start of the last sequence as variables. In the example you describe, the length of the sequence should be 50, the step size should be 10 and the start of the last sequence depends on the size of the input data and your needs.
>> startIndex = 10;
>> sequenceSize = 5;
>> finalSequenceStart = 20;
Create some sample data:
>> sampleData = randi(100, 1, 28)
sampleData =
Columns 1 through 18
8 53 10 82 82 73 15 66 52 98 65 81 46 44 83 9 14 18
Columns 19 through 28
40 84 81 7 40 53 42 66 63 30
Create a vector of the start indices of the sequences:
>> sequenceStart = startIndex:sequenceSize:finalSequenceStart
sequenceStart =
10 15 20
Create an array of indices to index into the data array:
>> index = cumsum(ones(sequenceSize, length(sequenceStart)))
index =
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
>> index = index + repmat(sequenceStart, sequenceSize, 1) - 1
index =
10 15 20
11 16 21
12 17 22
13 18 23
14 19 24
Finally, use this index array to reference the data array:
>> sampleData(index)
ans =
98 83 84
65 9 81
81 14 7
46 18 40
44 40 53
Use (start : step : end) indexing: v(1:1:50), v(10:1:60), etc. If the step is 1, you can omit it: v(1:50).
Consider the following vectorized code:
x = 1:100; %# an example sequence of numbers
nwind = 50; %# window size
noverlap = 40; %# number of overlapping elements
nx = length(x); %# length of sequence
ncol = fix((nx-noverlap)/(nwind-noverlap)); %# number of sliding windows
colindex = 1 + (0:(ncol-1))*(nwind-noverlap); %# starting index of each
%# indices to put sequence into columns with the proper offset
idx = bsxfun(#plus, (1:nwind)', colindex)-1; %'
%# apply the indices on the sequence
slidingWindows = x(idx)
The result (truncated for brevity):
slidingWindows =
1 11 21 31 41 51
2 12 22 32 42 52
3 13 23 33 43 53
...
48 58 68 78 88 98
49 59 69 79 89 99
50 60 70 80 90 100
In fact, the code was adapted from the now deprecated SPECGRAM function from the Signal Processing Toolbox (just do edit specgram.m to see the code).
I omitted parts that zero-pad the sequence in case the sliding windows do not evenly divide the entire sequence (for example x=1:105), but you can easily add them again if you need that functionality...

MATLAB: create new matrix from existing matrix according to specifications

Assume we have the following data:
H_T = [36 66 21 65 52 67 73; 31 23 19 33 36 39 42]
P = [40 38 39 40 35 32 37]
Using MATLAB 7.0, I want to create three new matrices that have the following properties:
The matrix H (the first part in matrix H_T) will be divided to 3 intervals:
Matrix 1: the 1st interval contains the H values between 20 to 40
Matrix 2: the 2nd interval contains the H values between 40 to 60
Matrix 3: the 3rd interval contains the H values between 60 to 80
The important thing is that the corresponding T and P will also be included in their new matrices meaning that H will control the new matrices depending on the specifications defined above.
So, the resultant matrices will be:
H_T_1 = [36 21; 31 19]
P_1 = [40 39]
H_T_2 = [52; 36]
P_2 = [35]
H_T_3 = [66 65 67 73; 23 33 39 42]
P_3 = [38 40 32 37]
Actually, this is a simple example and it is easy by looking to create the new matrices depending on the specifications, BUT in my values I have thousands of numbers which makes it very difficult to do that.
Here's a quick solution
[~,bins] = histc(H_T(1,:), [20 40 60 80]);
outHT = cell(3,1);
outP = cell(3,1);
for i=1:3
idx = (bins == i);
outHT{i} = H_T(:,idx);
outP{i} = P(idx);
end
then you access the matrices as:
>> outHT{3}
ans =
66 65 67 73
23 33 39 42
>> outP{3}
ans =
38 40 32 37