Error strtrim s argument must be a string or cellstring

Savannah is a central point for development, distribution and maintenance of free software, both GNU and non-GNU.

bug #34123: strtrim no longer trims multilevel cell arrays in some cases

Submitter:  Ben Barrowes <barrowes>
Submitted:  Wed 24 Aug 2011 06:25:03 PM UTC
 
Category:  Interpreter Severity:  3 — Normal
Priority:  5 — Normal Item Group:  Matlab Compatibility
Status:  Fixed Assigned to:  bpabbott
Originator Name:  barrowes Open/Closed:  * Closed
Release:  * dev Operating System:  * GNU/Linux
Fixed Release:  None Planned Release:  None

* Mandatory Fields

Add a New Comment (Rich Markup)
   

Comment Type & Canned Response:
   

   

( Jump to the original submission )

Mon 19 Sep 2011 09:37:06 PM UTC, comment #9: 

Matlab’s online docs can be read to imply that deblank behaves recursively.

«c = deblank(c) when c is a cell array of strings, applies deblank to each element of c.»

http://www.mathworks.com/help/techdoc/ref/deblank.html

I don’t see than implication on the other cellstr functions I looked at, so I think your conclusion is the correct thing to do.

Ben Abbott <bpabbott>
Project Member

Mon 19 Sep 2011 04:31:27 PM UTC, comment #8: 

Hmm.  Are we chasing Matlab undocumented behavior? 

The documentation doesn’t make it clear whether deblank and strtrim should work on nested cellstrings or just objects for which iscellstr() returns true.  I wonder if it varies by function whether the original programmer thought to code for this case.  This would explain why strtrim works in this case and strrep doesn’t.

In any case, I will code the same fix used here for deblank and then we can call it quits on Matlab compatibility for now.

Rik <rik5>
Project Administrator

Mon 19 Sep 2011 02:00:26 PM UTC, comment #7: 

I check ML’s iscellstr() function. It returns a false for multi-level cells of strings.

>> iscellstr (x)

ans =

     0

strrep() also fails in ML

>> x = {‘123X’, {‘X567’}};
>> strrep (x, ‘X’, ‘4’)
Error using strrep
Cell elements must be character arrays.

Ben Abbott <bpabbott>
Project Member

Mon 19 Sep 2011 12:36:56 PM UTC, comment #6: 

Rik, nice inference. Perhaps ML consistently treats cells of cells of strings as cellstings?

>> x = deblank ({‘123   ‘, {‘456  ‘}})

x =

    ‘123’    {1×1 cell}

>> length (x{2}{1})

ans =

     3

Ben Abbott <bpabbott>
Project Member

Mon 19 Sep 2011 05:08:48 AM UTC, comment #5: 

Sigh.  Yes, I was working on a private version of strtrim which accidentally got checked in.  I’ve checked in another changeset to rename the function.

Rik <rik5>
Project Administrator

Mon 19 Sep 2011 03:38:29 AM UTC, comment #4: 

Uhm, strtrim2? Is this accidental debug code that got committed?

http://hg.savannah.gnu.org/hgweb/octave/rev/a1049e4480f8#l1.8

Jordi Gutiérrez Hermoso <jordigh>
Project Administrator

Mon 19 Sep 2011 03:23:16 AM UTC, comment #3: 

Fixed in this changeset (http://hg.savannah.gnu.org/hgweb/octave/rev/a1049e4480f8) along the lines suggested by Ben.

Is there a similar issue in deblank()?

What does Matlab do for the following input

x = deblank ({«123   «, {«456  «}})
length (x{2}{1})

Rik <rik5>
Project Administrator

Sat 17 Sep 2011 01:41:10 AM UTC, comment #2: 

cc’n Rik

Ben Abbott <bpabbott>
Project Member

Sat 17 Sep 2011 01:35:42 AM UTC, comment #1: 

I tested the example with Matlab

>> aa = {‘ 123 ‘,{‘ fg’}}

aa =

    ‘ 123 ‘    {1×1 cell}

>> b = strtrim (aa)

b =

    ‘123’    {1×1 cell}

>> b{2}

ans =

    ‘fg’

I’ve attached a changeset. It looks a bit inelegant to me.

Is there a better way?

(file #23982)

Ben Abbott <bpabbott>
Project Member

Wed 24 Aug 2011 06:25:03 PM UTC, original submission:
 

The following just stopped working with the latest dev build. Nested cell arrays no longer get strtrim’ed properly:

debug> aa={‘ 123  ‘,{‘ fg’}}

aa =

{

  [1,1] =  123 

  [1,2] =

  {

    [1,1] =  fg

  }

}

debug> strtrim(aa)

error: strtrim: S argument must be a string or cellstring

error: called from:

error:   /usr/local/share/octave/3.5.0+/m/strings/strtrim.m at line -1, column -1

debug>

Ben Barrowes <barrowes>

(Note: upload size limit is set to 16384 kB, after insertion of
the required escape characters.)

Attach Files:
   
   

Comment:
   

Depends on the following items: None found

Items that depend on this one: None found

Carbon-Copy List

  • -email is unavailable- added by jordigh (Posted a comment)
  • -email is unavailable- added by rik5 (Posted a comment)
  • -email is unavailable- added by bpabbott (Rik, can you comment on this bug report?)
  • -email is unavailable- added by bpabbott (Updated the item)
  • -email is unavailable- added by barrowes (Submitted the item)
  • There are 0 votes so far. Votes easily highlight which items people would like to see resolved
    in priority, independently of the priority of the item set by tracker
    managers.

    Only project members can vote.

    Please enter the title of George Orwell’s famous
    dystopian book (it’s a date):

    Back to the top

    Praveen Choudhury

    • Direct link to this question

     ⋮ 

    • Direct link to this question

    I have a cell of 472*12 size. I am trying to use strtrim on this cell but I am getting an error which says «Input should be a string or a cell array of strings.» Can anyone help me with this?

      4 Comments

    Image Analyst

    Direct link to this comment

     ⋮ 

    • Link

      Direct link to this comment

    Probably, if we could see your code. Have you read this yet?

    Geoff Hayes

    Direct link to this comment

     ⋮ 

    • Link

      Direct link to this comment

    Praveen — please describe the contents for this cell array. Are all elements strings or do some include numeric elements? Based on the error message, I am assuming that the latter is true. If that is the case, you will have to apply strtrim to just those elements of the cell array that are strings.

    Praveen Choudhury

    Direct link to this comment

     ⋮ 

    • Link

      Direct link to this comment


    • q1.JPG

    All my elements are of type char. Please see the attached.

    Geoff Hayes

    Direct link to this comment

     ⋮ 

    • Link

      Direct link to this comment

    They appear to be either character strings or are empty [] elements. See Sean’s answer below for how to deal with this situation (his code replaces the empty elements with » strings).

    Sign in to comment.

    Accepted Answer

    Walter Roberson

    • Direct link to this answer

     ⋮ 

    • Direct link to this answer

    [] is not of type char so you are current attempting to use strtrim on non-strings.

    Here is a workaround:

    new_tableData = cellfun(@(S) strtrim([S »]), tableData, ‘Uniform’, 0);

    The [] of » has no effect on strings, but has the subtle side effect of converting [] into » which can be trimmed.


    More Answers (1)

    Sean de Wolski

    • Direct link to this answer

     ⋮ 

    • Direct link to this answer

    will definitively tell you if your cell contains only strings. It’s also possible that it contains numeric empties [] but otherwise strings. If this is the case the following will fix it.

    empties = cellfun(@isempty,your_cell)

    your_cell(empties) = {»};

    Note you could also create the cell this way to begin with rather than using cell()

    your_cell = repmat({»},rows,cols);

    See Also

    Categories

    Community Treasure Hunt

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

    Start Hunting!

    An Error Occurred

    Unable to complete the action because of changes made to the page. Reload the page to see its updated state.

    MathWorks - Domain Selector

    0 / 0 / 0

    Регистрация: 30.05.2021

    Сообщений: 4

    1

    28.04.2022, 22:28. Показов 974. Ответов 3


    Доброго времени суток!
    Столкнулся с проблемой типа переменной
    Если кратко, в самом коде просто есть функция input
    При этом она почему-то автоматически преобразует значение в future (хотя в теории туда должны вводиться числа и потом переходить во float)

    Ошибка такая:

    TypeError Traceback (most recent call last)
    Input In [1], in <cell line: 4>()
    2 import numpy as np
    3 print(‘Введите значени а =’)
    —-> 4 k=float(input())
    5 print(type(k))
    6 print(‘aaa’)

    TypeError: float() argument must be a string or a real number, not ‘Future’

    Полный код программы:

    Код

    import math
    import numpy as np
    print('Введите значени а =')
    k=float(input())
    print(type(k))
    print('aaa')
    print('Введите начало и конец промежутка')
    a=input('Начало = ')
    a=float()
    b=input('Конец = ')
    b=float()
    print('y принадлежит от ',a,' до ',b)
    y=input('Введите значение дельта y ')
    y=float()
    m=float((b-a)/k)+1
    n=3*m
    n=int(n)
    m=int(m)
    B= np.arange(n).reshape(m,3)
    B = B.astype("float")
    for i in range(0,m):
        B[i][0]=a+(i*k)
    for c in range(0,m):
        B[c][1]=float(B[c][1])
        B[c][1]=(float)((2**(1-B[c][0]))-(2.5*math.cos(k)))
    for z in range(0,m):
        B[z][2]=float(B[z][2])
        B[z][2]=(float)((math.log((math.fabs(B[z][0]-1)),10))+(B[z][1])**2)
    print('Значение y      Значение x     Значение w ')
    print(B)

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    Programming

    Эксперт

    94731 / 64177 / 26122

    Регистрация: 12.04.2006

    Сообщений: 116,782

    28.04.2022, 22:28

    3

    Semen-Semenich

    4046 / 2986 / 1076

    Регистрация: 21.03.2016

    Сообщений: 7,514

    29.04.2022, 14:21

    2

    Python
    1
    2
    
    a=input('Начало = ')
    a=float() # ??? что то тут не так. вам  не кажется?

    о чем вам и говорит ошибка. аргумент функции float должен быть строкой или реальным числом

    Python
    1
    
    a = float(input('Начало = '))

    и так для всех ваших переменных



    0



    0 / 0 / 0

    Регистрация: 30.05.2021

    Сообщений: 4

    29.04.2022, 15:33

     [ТС]

    3

    Прошу прощения, не тот код скопировал, вот нормальный, но будет та же ошибка, что думаете?

    Код

    import math
    import numpy as np
    print('Введите значени а =')
    k=float(input())
    print('Введите начало и конец промежутка')
    a=input('Начало = ')
    a=float(a)
    b=input('Конец = ')
    b=float(b)
    print('y принадлежит от ',a,' до ',b)
    y=input('Введите значение дельта y ')
    y=float(y)
    m=float((b-a)/k)+1
    n=3*m
    n=int(n)
    m=int(m)
    B= np.arange(n).reshape(m,3)
    B = B.astype("float")
    for i in range(0,m):
        B[i][0]=a+(i*k)
    for c in range(0,m):
        B[c][1]=float(B[c][1])
        B[c][1]=(float)((2**(1-B[c][0]))-(2.5*math.cos(k)))
    for z in range(0,m):
        B[z][2]=float(B[z][2])
        B[z][2]=(float)((math.log((math.fabs(B[z][0]-1)),10))+(B[z][1])**2)
    print('Значение y      Значение x     Значение w ')
    print(B)

    Даже если так, то будет та же ошибка

    TypeError Traceback (most recent call last)
    Input In [1], in <cell line: 4>()
    2 import numpy as np
    3 print(‘Введите значени а =’)
    —-> 4 k=float(input())
    5 print(‘Введите начало и конец промежутка’)
    6 a=input(‘Начало = ‘)

    TypeError: float() argument must be a string or a real number, not ‘Future’



    0



    Semen-Semenich

    4046 / 2986 / 1076

    Регистрация: 21.03.2016

    Сообщений: 7,514

    30.04.2022, 12:08

    4

    у меня с вводом ошибок нет. дальше при построении матрицы выходит но к этой ошибки отношения не имеет.

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    print('Введите значени а =')
    k=float(input())
    print('Введите начало и конец промежутка')
    a=input('Начало = ')
    a=float(a)
    b=input('Конец = ')
    b=float(b)
    print('y принадлежит от ',a,' до ',b)
    y=input('Введите значение дельта y ')
    y=float(y)
    m=float((b-a)/k)+1
    n=3*m
    n=int(n)
    m=int(m)

    результат без ошибок

    Bash
    1
    2
    3
    4
    5
    6
    7
    8
    
    Введите значени а =
    12
    Введите начало и конец промежутка
    Начало = 32
    Конец = 55
    y принадлежит от  32.0  до  55.0
    Введите значение дельта y 40
    >>>

    я вам уже выше показал как получать ввод требуемого типа. зачем по 10 строк переводить в требуемый тип? запустите кода ниже у себя. будет ошибка или нет

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    print('Введите значение а =')
    k=float(input())
    print('Введите начало и конец промежутка')
    a = float(input('Начало = '))
    b = float(input('Конец = '))
    print('y принадлежит от ',a,' до ',b)
    y = float(input('Введите значение дельта y '))
    m = float((b-a)/k)+1
    n = int(3*m)
    m = int(m)
     
    print(n, m)



    0



    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    30.04.2022, 12:08

    Помогаю со студенческими работами здесь

    Flask. TypeError: 1 required positional argument: ‘self’
    Привет. Использую flask для своей веб службы, написал класс, который имеет примерно одинаковые…

    TypeError: preveiw_files() takes 1 positional argument but 2 were given
    Добрый день. Не так давно начал осваивать Python, в том числе и создание графического интерфейса….

    TypeError: list.append() takes exactly one argument (3 given)
    Код:

    my_family =
    my_family.append(‘M’, ‘D’, ‘S’,)

    my_family_height.insert(1, 165)…

    TypeError: add() argument after * must be an iterable, not Settings
    Здравствуйте. Никак не могу понять, как исправить эту ошибку. Пишу программу по книге, код верный,…

    TypeError: argument 1 must be pygame.Surface, not str
    Нужно было сделать игру танчики. Почти сделал и хотел бы вывести счетчик жизней но выводит ошибку

    TypeError: __getCoordX() takes 1 positional argument but 2 were given
    Подскажите, что не так с моим кодом. При его запуске вызывается ошибка :
    TypeError: __getCoordX()…

    Искать еще темы с ответами

    Или воспользуйтесь поиском по форуму:

    4

    Удалите начальный и конечный пробел из строк

    Синтаксис

    Описание

    пример

    newStr = strtrim(str) удаляет начальные и конечные пробельные символы из str и возвращает результат как newStr. Однако strtrim не удаляет значимые пробельные символы. Например, strtrim удаляет начальный и конечный пробел и символы табуляции, но не удаляет символ неразрывного пробела, char(160).

    Примеры

    свернуть все

    Удаление ведущего пробела из вектора символа

    Создайте вектор символов с пробелами и символом табуляции как ведущий пробел.

    chr = sprintf('  t   Remove    leading whitespace')
    chr = 
    '  	   Remove    leading whitespace'
    

    Удалите начальные табуляцию и пробелы.

    newChr = 
    'Remove    leading whitespace'
    

    strtrim удаляет ведущие пробельные символы, но не пробел между другими символами.

    Удаление начальных и конечных пробелов из массива строк

    Начиная в R2017a, можно создать строки с помощью двойных кавычек. Создайте массив строк и удалите начальный и конечный пробел с strtrim функция.

    str = ["   Gemini    ","   Apollo    ";
           "   ISS       ","   Skylab    "]
    str = 2x2 string
        "   Gemini    "    "   Apollo    "
        "   ISS       "    "   Skylab    "
    
    
    newStr = 2x2 string
        "Gemini"    "Apollo"
        "ISS"       "Skylab"
    
    

    Удаление ведущий и запаздывание пробела от массива ячеек

    Удалите начальный и конечный пробел из всех векторов символов в массиве ячеек и отобразите их.

    chr = {'     Trim leading whitespace';
           'Trim trailing whitespace     '}
    chr = 2x1 cell
        {'     Trim leading whitespace' }
        {'Trim trailing whitespace     '}
    
    
    newChr = 2x1 cell
        {'Trim leading whitespace' }
        {'Trim trailing whitespace'}
    
    

    Хранение символа неразрывного пробела

    Создайте вектор символов, который включает символ неразрывного пробела, char(160), как конечный пробельный символ.

    chr = '     Keep nonbreaking space';
    chr = [chr char(160) '     '];

    Отобразите chr между | символы, чтобы показать начальный и конечный пробел.

    ans = 
    '|     Keep nonbreaking space |'
    

    Удалите начальные и конечные пробельные символы.

    Отобразите newChr между | символы. strtrim удаляет пробелы, но оставляет неразрывный пробел в конце newChr.

    ans = 
    '|Keep nonbreaking space |'
    

    Входные параметры

    свернуть все

    strВведите текст
    символьный массив | массив ячеек символьных массивов | массив строк

    Введите текст в виде символьного массива или как массив ячеек символьных массивов или массив строк.

    Алгоритмы

    strtrim не удаляет значимые пробельные символы.

    Эта таблица показывает наиболее распространенные символы, которые являются значимыми пробельными символами и их описаниями. Для получения дополнительной информации смотрите Пробельный символ.

    Значимый пробельный символ

    Описание

    char(133)

    Следующая строка

    char(160)

    Неразрывный пробел

    char(8199)

    Пробел, равный по ширине цифрам

    char(8239)

    Узкий пробел без пропусков

    Расширенные возможности

    «Высокие» массивы
    Осуществление вычислений с массивами, которые содержат больше строк, чем помещается в памяти.

    Генерация кода C/C++
    Генерация кода C и C++ с помощью MATLAB® Coder™.

    Указания и ограничения по применению:

    • Входной текст должен быть строковым скаляром или символьным массивом.

    • Входные значения должны быть в области значений 0–127.

    • Сгенерированный код возвращает пустой выходной параметр как символьный массив 1 на 0.

    Основанная на потоке среда
    Запустите код в фоновом режиме с помощью MATLAB® backgroundPool или ускорьте код с Parallel Computing Toolbox™ ThreadPool.

    Эта функция полностью поддерживает основанные на потоке среды. Для получения дополнительной информации смотрите функции MATLAB Запуска в Основанной на потоке Среде.

    Распределенные массивы
    Большие массивы раздела через объединенную память о вашем кластере с помощью Parallel Computing Toolbox™.

    Указания и ограничения по применению:

    • str должен быть массив строк или массив ячеек из символьных векторов.

    Для получения дополнительной информации смотрите функции MATLAB Запуска с Распределенными Массивами (Parallel Computing Toolbox).

    Представлено до R2006a

    You cannot convert a list to a floating-point number. If you try to pass a list as an argument to the built-in float() method, you will raise the TypeError: float() argument must be a string or a number, not ‘list’.

    If you want to convert the elements of a list to floats, you can use the map() function. For example,

    a_list = list(map(float, a_list))

    We can also use list comprehension to create a new list of floating-point numbers.

    This tutorial will go through the error in detail and how to solve it with code examples.


    Table of contents

    • TypeError: float() argument must be a string or a number, not ‘list’
    • Example
      • Solution #1: Use the map() function
      • Solution #2: Use List Comprehension
    • Summary

    TypeError: float() argument must be a string or a number, not ‘list’

    A TypeError occurs when you perform an operation with an invalid data type. The built-in float() method accepts a string or a number. If you pass a list to the float() method, this is an invalid data type and will raise the TypeError.

    Example

    Let’s look at an example where we have a list of numeric strings. We want to convert the list to a list of floating-point numbers.

    a_list = ["2.1", "5.4", "0.7", "0.04", "1.0"]
    
    float_list = float(a_list)
    
    print(float_list)

    Let’s run the code to see what happens:

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    Input In [5], in <cell line: 3>()
          1 a_list = ["2.1", "5.4", "0.7", "0.04", "1.0"]
    ----> 3 float_list = float(a_list)
          5 print(float_list)
    
    TypeError: float() argument must be a string or a number, not 'list'

    The error occurs because we passed a list to the float() method, which is an invalid data type to convert to a floating-point number.

    Solution #1: Use the map() function

    We can use the built-in map function to solve this error. The map function returns an iterator that applies a function to every item of an iterable. In our case, the function we want to apply is float() and the iterable is our list a_list. Applying the float() function to each element in the list is possible because the elements are strings.

    The map() function returns a map object which is an iterator. We can convert the map object to a list using the list() function.

    Let’s look at the revised code:

    a_list = ["2.1", "5.4", "0.7", "0.04", "1.0"]
    
    float_list = list(map(float, a_list))
    
    print(float_list)
    [2.1, 5.4, 0.7, 0.04, 1.0]

    We successfully converted the list of strings to a list of floats.

    Solution #2: Use List Comprehension

    List comprehension provides a way to create a new list based on the values of an existing list. We can use list comprehension to convert a list of strings to a list of floating-point numbers. Let’s look at the revised code:

    a_list = ["2.1", "5.4", "0.7", "0.04", "1.0"]
    
    float_list = [float(x) for x in a_list]
    
    print(float_list)

    Let’s run the code to get the result:

    [2.1, 5.4, 0.7, 0.04, 1.0]

    If we want to convert an individual element, we can use the subscript operator [] to get individual elements of the list. For example,

    number = float(a_list[0])
    
    print(number)
    2.1
    

    Summary

    Congratulations on reading to the end of this tutorial! The TypeError: float() argument must be a string or a number, not ‘list’ occurs if you try to convert a list object to a floating-point number. We can apply the map() function to apply float() to each element in the list, or we can use list comprehension.

    For further reading on converting values using built-in functions, go to the article: How to Solve Python TypeError: int() argument must be a string, a bytes-like object or a number, not ‘list’
    Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

    Have fun and happy researching!

    @thearn

    First of all, great library! I’m finding it very useful for some projects that I am working on.
    However, in some instances I am running into a TypeError in models where an array is being sliced or assigned as a block within a larger array (despite being scalar functions ultimately).

    I can reproduce it with a stripped-down example:

    https://gist.github.com/thearn/faba933208316d71cdb9

    import autograd.numpy as np
    from autograd import grad
    
    def f(A):
    
        B = np.zeros((4,4))
    
        B[:2, :2] = A
    
        return B.sum()
    
    A = np.random.randn(2,2)
    
    df = grad(f)
    
    print df(A)
    
    # expected: [[ 1.,  1.],[ 1.,  1.]]

    which gives the traceback:

    Traceback (most recent call last):
      File "/Users/tristanhearn/Dropbox/code/adcomponent/src/adcomponent/test.py", line 17, in <module>
        print df(A)
      File "/Users/tristanhearn/Documents/thearn_repos/autograd/autograd/core.py", line 20, in gradfun
        return backward_pass(*forward_pass(fun,args,kwargs,argnum))
      File "/Users/tristanhearn/Documents/thearn_repos/autograd/autograd/core.py", line 61, in forward_pass
        end_node = fun(*args, **kwargs)
      File "/Users/tristanhearn/Dropbox/code/adcomponent/src/adcomponent/test.py", line 9, in f
        B[:2, :2] = A
    TypeError: float() argument must be a string or a number
    

    Is this expected (ie. a known and accepted limitation)?

    @duvenaud

    Thanks for the encouragement, and for making a minimal working example!

    This is indeed a known limitation of autograd — indexed assignment isn’t yet supported, unfortunately. You can usually get around this by building a list and calling np.concatenate().

    We’ll add a try/catch block to give a more informative error message when this occurs.

    Also, we’d love to hear about what you’re using autograd for, and if you have any other feature requests.

    mattjj

    added a commit
    that referenced
    this issue

    Nov 5, 2015

    @mattjj

    @thearn

    Also, we’d love to hear about what you’re using autograd for, and if you have any other feature requests.

    I’m writing an auto-differentiating component for NASA’s OpenMDAO framework. This will make it much easier to quickly & automatically provide numerical derivates across coupled engineering codes (without the potential instability of finite-difference approximations), which is very important for numerical optimization or sensitivity analysis. There are other alternatives as well (complex-step approximation, or closed-form specification of derivates of course), but AD has been on our radar for awhile.

    Unfortunately, some of our disciplinary analysis codes (engine cycle analysis in particular) do use indexed assignment in a few places, so my AD component isn’t quite as general as I had hoped at the moment. But not all of our components require this.

    Also, looking through the source, it looks like you guys have implemented a jacobian function (which I did as well). I wish I had noticed that before! :)

    Again, awesome library 👍

    @mattjj

    Wow, sounds very cool! I hope autograd continues to help. Also, the more reasons we have to make indexed assignment work, the more impetus we’ll have to figure out an implementation.

    By the way, there are currently two jacobian functions, one in core.py and another in convenience_wrappers.py. The one in core.py is better in at least three ways: it’s faster (only one forward pass is done), it avoids repeated prints or side-effects (also because of the single forward pass), and it’s more general (it can take jacobians of jacobians, which I think the wrapper version can’t do). I’ll probably delete the version in convenience_wrappers.py sometime today (unless someone protests).

    @mattjj

    Another by the way: on the current master branch, the error message produced by the code in your original test case should be somewhat clearer!

    [... snip traceback ...]
    
    /Users/mattjj/packages/autograd/issue58.py in f(x)
          6 def f(x):
          7     A = np.zeros((4,4))
    ----> 8     A[:2,:2] = x
          9     return A.sum()
         10
    
    AutogradException: autograd doesn't support assigning into arrays
    Sub-exception:
    TypeError: float() argument must be a string or a number
    

    @ziyuang

    @duvenaud what does it mean by «building a list and calling np.concatenate()»?

    @mattjj

    In the case of the OP’s code, I think he means rewriting lines like this:

    B = np.zeros((4,4))
    B[:2, :2] = A

    as something like this:

    row1 = np.concatenate([A, np.zeros((2,2))], axis=1)
    row2 = np.zeros((2, 4))
    B = np.concatenate([row1, row2], axis=0)

    In general, instead of building arrays by allocating zeros and then assigning into blocks, you can instead build the blocks as separate arrays and then concatenate them. The latter method works with autograd, but the former method doesn’t.

    @ziyuang

    @mattjj Can I give B a correct data type such that it can hold the autograd nodes? (Or is data type the cause of issue?)

    @mattjj

    No, autograd doesn’t support assignment into arrays. We could overload indexed assignment, but it would require a substantial amount of internal bookkeeping, and it might even obfuscate what happens when the program runs. In particular, to do reverse-mode autodiff, the intermediate values computed during the evaluation of the function need to be stored because they usually need to be read during the backward pass computation. Since assignment into arrays might clobber intermediate values, whenever an assignment happens we’d need to copy that data somewhere for use in the backward pass. Instead, by not supporting assignment, we basically force the user to be explicit about when this kind of copying happens.

    If you need to use assignment, one thing you can do is mark your function as a primitive and then define its vjp manually. Within a primitive you’re just using naked numpy, so assignment works. In the case of the OP’s code, which might be too simplified to be interesting, that might look something like

    import autograd.numpy as np
    from autograd import grad
    from autograd.core import primitive
    
    @primitive
    def f(A):
        B = np.zeros((4, 4))
        B[:2, :2] = A
        return B.sum()
    
    def f_vjp(g, ans, vs, gvs, A):
        return g * np.ones((2, 2))
    
    f.defvjp(f_vjp)

    @BassantTolba1234

    Dear Sir ,
    Thank you for your efforts,
    Please this is my part of code , when I try to run these lines , this error appears please can you kindly help me to solve it please ?

    def interpolation(noisy , SNR , Number_of_pilot , interp):

    noisy_image = np.zeros((40000,72,14,2))
    
    
    
    noisy_image[:,:,:,0] = np.real(noisy)
    
    noisy_image[:,:,:,1] = np.imag(noisy)
    

    TypeError: float() argument must be a string or a number, not ‘dict’

    STRTRIM

    Tip: See also the IDL_String::Trim method, which provides similar functionality but with an object-oriented interface.

    The STRTRIM function removes leading and/or trailing blank from the input String.

    Examples


    Converting variables to string type often results in undesirable leading blanks. For example, the following command converts the integer 56 to string type:

    C = STRING(56)

    Entering the command:

    HELP, C

    IDL prints:

    C         STRING = '      56'

    which shows that there are six leading spaces before the characters 5 and 6. To remove these leading blanks, enter the command:

    C = STRTRIM(C, 1)

    To confirm that the blanks were removed, enter:

    HELP, C

    IDL prints:

    C         STRING = '56'

    Syntax


    Result = STRTRIM( String [, Flag] )

    Return Value


    Returns a copy of string with the specified blank spaces removed.

    Arguments


    String

    The string to have leading and/or trailing blanks removed. If this argument is not a string, it is converted using IDL’s default formatting rules. If it is an array, the result is an array with the same structure where each element contains a trimmed copy of the corresponding element of String.

    Flag

    A value that controls the action of STRTRIM. If Flag is zero or not present, trailing blanks are removed. Leading blanks are removed if it is equal to 1. Both are removed if it is equal to 2.

    Version History


    Original

    Introduced

    See Also


    String Operations, String Processing, STRCOMPRESS, STRMID, STRPOS, STRPUT, STRSPLIT, IDL_String

    Понравилась статья? Поделить с друзьями:
  • Error strlen was not declared in this scope
  • Error strings dat file not found
  • Error string or binary data would be truncated the statement has been terminated
  • Error string index out of range java
  • Error string in namespace std does not name a type