how to convert a number array to a single string in matlab - arrays

How can i convert a numeric array to a single string, where array numbers will be separated with a comma ?
(e.g. convert A=[1 2 3] to a string '1,2,3')
Moreover, is there any way to apply the same above in case that matrix A contains variables in a for loop?
(e.g.
for i=1,10
A(i)=[1 1 i+1];
end
As variable i varies, I need to obtain a string '1,1,i+1'
thanks a lot !

There is a num2str() function
>> test =[123 124 125] % 3 element vector
test =
123 124 125
>> num2str(test) % 1 element string
ans =
123 124 125
and also a function to write ASCII delimited files
the process can easily be reversed with the str2num function, as dan pointed out

I think you need this:
for i=1:10
disp(['1,1,',num2str(i+1)])
end
Note: Try to avoid 'i' as the iteration variable.
The output:
1,1,2
1,1,3
1,1,4
1,1,5
1,1,6
1,1,7
1,1,8
1,1,9
1,1,10
1,1,11

for i=1:10
s = sprintf('%d,', A);
S{i} = s(1:end-1);
end

The function mat2str does just that:
>> A = [1 2 3];
>> mat2str(A)
ans =
[1 2 3]

Related

Taking x number integers and putting them into an array

I need to take x amount of input lines (x is specified by the user) then put them into a 2d array. Each line contains x amount of integers separated by spaces.
For example;
Input:
3
4 3 1
6 5 2
9 7 3
I need to take that input and put them into a 2d array, how do I do this?
Assuming your numbers are separated exactly by one space:
n = int(input('enter size'))
print([[int(i) for i in input().split(' ')]
for __ in range(n)])
Suppose you have your input stored in a file named 'input.txt'
n=2 #number specified by user
with open('input.txt', 'r') as file:
result = [[int(char) for char in lines.split(' ')]for lines in file.read().splitlines()[:2*n:2] ]

how to output on ruby, two input in one single line

I need output two different array (or range ) which both of them takes by gets.chomp, one of them a string, the other must be integer. But i dont want to transpoze or i dont want to use zip method. because when i take output one of them in a row, the other might be reverse two or more times.
name = $name
num = $num
arr = $arr
puts "num?"
num = gets.chomp.to_i
arr = []
for x in (1..num)
puts "#{x}. name? " #its can be "A" ,"B","C"
name = gets.chomp.to_sym
arr.push (name)
end
for y in (1..100)
arr.each do |z|
print y, " " , z, "\n"
end
end
# i want to outputs like this :
1 A
2 B
3 C
4 A
5 B #reverse time (%5 == 0)
6 A
7 C
8 B
9 A
10 C #reverse time (%5 ==0)
11 A
integers dont reverse anytime, but Strings must be reverse...
Thanks for help..
Rather than using a nested loop, you want to pair your integer Range with your name Array, and then loop over the resulting Array of Arrays. In Ruby we can do this using the #zip method. Also, because the name array may not fill up the entire Range, we can #cycle the name array to convert it to a repeating Enumerator (otherwise, in the example given, 3 through 5 would be paired with nil).
>> arr = ["John", "Jane"]
>> pairs = (1..5).zip(arr.cycle)
#> [[1, "John"], [2, "Jane"], [3, "John"], [4, "Jane"], [5, "John"]]
>> pairs.each { |integer, name| print "#{integer} #{name}\n" }
1 John
2 Jane
3 John
4 Jane
5 John

Counting rows without any NaNs in a struct

I need to count how many structs do not have any NaNs across all fields in an array of structures. The sample struct looks like this:
a(1).b = 11;
a(2).b = NaN;
a(3).b = 22;
a(4).b = 33;
a(1).c = 44;
a(2).c = 55;
a(3).c = 66;
a(4).c = NaN;
The output looks like this
Fields b c
1 44 11
2 55 NaN
3 66 22
4 NaN 33
The structs without NaNs are 1 and 3, so there should be 2 in total here.
I tried using size(a, 2), but it just tells me the total number of structs in the array. I need it to calculate N (the number of observations in the sample). NaNs don't count as observations as they are omitted in the analysis.
What is the simplest way to count structs without any NaNs in a struct array?
I would suggest using the following one-line command:
nnz(~any(cellfun(#isnan,struct2cell(a))))
struct2cell(a) converts your struct into the 3D cell array
cellfun(#isnan,___) applies isnan to each element of cell array
~any(__) works along first dimension and returns arrays that have no NaNs
nnz(__) counts how many rows have no NaNs
The result is just a number, 2 in this case.
The following:
find(~any(cellfun(#isnan,struct2cell(a))))
Would tell you which rows are without NaNs
This will tell you which ones have no NaNs
for ii=1:size(a,2)
hasNoNaNs(ii)=~any(structfun(#isnan,a(ii)));
end
The way it works is iterates trhoug each of the structures, and use structfun to call isnan in each of the elements of it, then checks if any of them is a NaN and negates the result, thus giving 1 in the ones that have no NaNs
Because bsxfun is never the wrong approach!
sum(all(bsxfun(#le,cell2mat(struct2cell(a)),inf)))
How this works:
This converts the struct to a cell, and then to a matrix:
cell2mat(struct2cell(a))
ans(:,:,1) =
11
44
ans(:,:,2) =
NaN
55
ans(:,:,3) =
22
66
ans(:,:,4) =
33
NaN
Then it uses bsxfun to check which of those elements are less than, or equal to zero. The only value that doesn't satisfy this condition is NaN.
bsxfun(#le,cell2mat(struct2cell(a)),inf)
ans(:,:,1) =
1
1
ans(:,:,2) =
0
1
ans(:,:,3) =
1
1
ans(:,:,4) =
1
0
Then, we check if all the values in each of those slices are true:
all(bsxfun(#le,cell2mat(struct2cell(a)),inf))
ans(:,:,1) =
1
ans(:,:,2) =
0
ans(:,:,3) =
1
ans(:,:,4) =
0
And finally, we sum it up:
sum(all(bsxfun(#le,cell2mat(struct2cell(a)),inf)))
ans =
2
(By the way: It's possible to just skip the bsxfun, but where's the fun in that)
sum(all(cell2mat(struct2cell(a))<=inf))
Use arrayfun to iterate over a and structfun to iterate over fields and you get a logical array of elements that do not have NaNs:
>> arrayfun(#(x) ~any(structfun(#isnan, x)), a)
ans =
1 0 1 0
Now you can just sum it
>> sum(arrayfun(#(x) ~any(structfun(#isnan, x)), a))
ans =
2
Taking the idea from this not working answer to use comma separated lists:
s=sum(~any(isnan([[a.b];[a.c]])));
It may look very dumb to hard-code the field names but it leads to fast code because it avoids both iterating and cell arrays.
Generalizing this approach to arbitriary field names, you end up with this solution:
n=true(size(a));
for f = fieldnames(a).'
n(isnan([a.(f{1})]))=false;
end
n=sum(n(:));
Assuming that you have a large struct with only few fieldnames this is very efficient, because it is only iterating the fieldnames.
Third solution maybe - may not be elegant depending on your data:
A = [[a.b];[a.c]]; %//EDIT -- Fixed based on #Daniel's correct solution
IndNotNaN = find (~isnan(A));
Depends if you have lots of structs you will have to concatenate a.b, a.c ....a.n

I want to convert the char matrix into numbers in matlab

I want to convert the string into numbers for example x=[abacaaaabb] I want to assign values a=1 b=2 and c=-1 and store in new matrix x=[1 2 1 -1....}
You can create a mapping:
map = zeros(1,256);
map('abc') = [1, 2, -1];
Then you can just index it with your input:
x = 'abacaaaabb';
mx = map(x);
A simpler way (unless your mapping really does have to be arbitrary like in your example):
x=['abacaaaabb'];
num = x - 96
results in
num =
1 2 1 3 1 1 1 1 2 2

find and replace values in cell array

I have a cell array like this: [...
0
129
8...2...3...4
6...4
0
I just want to find and replace specific values, but I can't use the ordinary function because the cells are different lengths. I need to replace many specific values at the same time and there is no general function about how values are replaced. However, sometimes several input values should be replaced by the same output.
so I want to say
for values 1:129
'if 0, then 9'
'elseif 1 then 50'
'elseif 2 or 3 or 4 then 61'
etc...up to 129
where these rules are applied to the entire array.
I've tried to work it out myself, but still getting nowhere. Please help!
Since your values appear to span the range 0 to 129, one solution is to add one to these values (so they span the range 1 to 130) and use them as indices into a vector of replacement values. Then you can apply this operation to each cell using the function CELLFUN. For example:
>> C = {0, 129, [8 2 3 4], [6 4], 0}; %# The sample cell array you give above
>> replacement = [9 50 61 61 61 100.*ones(1,125)]; %# A 1-by-130 array of
%# replacement values (I
%# added 125 dummy values)
>> C = cellfun(#(v) {replacement(v+1)},C); %# Perform the replacement
>> C{:} %# Display the contents of C
ans =
9
ans =
100
ans =
100 61 61 61
ans =
100 61
ans =
9

Resources